$(".button-toggle").click(function(e){
$(this).parents.find('#second').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first">
<a href="#" class="buttong-toggle">
<button>Show/Hide</button>
</a>
</div>
<div id="second">
larger section
</div>
正如你从小提琴中可以看出的那样,这是行不通的。我试图找出如何遍历DOM,因为'this'事件不会在整个DOM的上下文中运行,所以我想它找不到#second ID
答案 0 :(得分:1)
正确的代码: https://jsfiddle.net/orttv29j/
修正:
(You don't need to know where the target element is located whether in the same parent container or other, javascript does that itself by obtaining their id or class name as passed in the toggle function)
$(".button-toggle").click(function(e){
$("#second").toggle();
});
#first{
background-color: dodgerblue;
min-height: 100px;
margin: 20px;
}
#second{
background-color: gray;
min-height: 200px;
margin: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first">
<a href="#" class="button-toggle">
<button>Click</button>
</a>
</div>
<div id="second">
larger section
</div>
答案 1 :(得分:1)
以下是一些信息更改 - 班级名称:&#39; buttong-toggle&#39;应该是按钮切换&#39; $(this).parents - 是函数不会得到所需的结果需要使用$(this).parents() - 这是对象 以下是完成的更改。
$(".button-toggle").click(function(e){
$(this).parents().find('#second').toggle();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first">
<a href="#" class="button-toggle">
<button>Show/Hide</button>
</a>
</div>
<div id="second">
larger section
</div>
&#13;