jQuery toggle multiple classes

丶灬走出姿态 提交于 2019-12-08 03:45:26

问题


I want to Show/Hide multiple divs on the same class using jQuery toggle.

Currently, the button show/hides all divs. How can I make it toggle one div without making the class unique? Fiddle demo.

jQuery:

$(".button").click(function() {
    $(".comment").toggle();
});

HTML:

<div class="comment">
    Comment 1
</div>
<button class="button">Show Comment</button>
<br/>
<div class="comment">
    Comment 2
</div>
<button class="button">Show Comment</button>

回答1:


You need to find the comment relative to the element clicked. In your case it is the previous element to the button, so use prev() with $(this) (which is the button clicked):

JSFiddle: http://jsfiddle.net/TrueBlueAussie/vgs2wsz2/1/

$(".button").click(function() {
    $(this).prev(".comment").toggle();
});

Note: The ".comment" in prev() is not needed in this case, but makes it more obvious.

e.g. this will do the same:

$(".button").click(function() {
    $(this).prev().toggle();
});


来源:https://stackoverflow.com/questions/27785317/jquery-toggle-multiple-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!