如何在HTML中使用JavaScript在类之前和之后获取元素?

时间:2018-10-19 21:12:09

标签: javascript jquery html dom

我坚持使用简单的功能。

说说,作为示例HTML结构:

<button class="accordion" onclick="myfunction-show-hide()">show or hide</button>
<div class="inner"style="display:none"> What I want to show/hide>
<button class="accordion" onclick="myfunction-hide()">hide</button>
</div>

我想构建一个函数myfunction-show-hide(),该函数选择类NEXT的{​​{1}}格,并将其显示更改为inner(如果是'',则更改为{ {1}}(如果是none

还有反向函数,作用在类none的{​​{1}} div上。

声音真的很简单,但是我被卡住了!

谢谢您的帮助。

***** ****下方的无效代码

''

另一个不工作:

PREVIOUS

}

inner

}

另一个不工作:

    <button class="accordion" onclick="myfunction-show-hide()">show or hide</button>
<div class="inner"style="display:none"> What I want to show/hide>
<button class="accordion" onclick="myfunction-hide()">hide</button>
</div>

<script

  function myfunction-show-hide(){
    var x =  this.nextElementSibling;
    if (x.style.display == "none")
    {x.style.display = "";}
    else
    {x.style.display = "none"}

}
function myfunction-hide(){
    this.prev().hide(); 

}</script>

1 个答案:

答案 0 :(得分:0)

我认为这会对您有所帮助:

function myfunction_show_hide(){
	$(this).next().toggle();
}

function myfunction_hide(){
	$(this).prev().hide();	
}
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

  <button class="accordion" onclick="myfunction_show_hide()">show or hide</button>
<div class="inner"> What I want to show/hide</div>
<button class="accordion" onclick="myfunction_hide()">hide</button>