作为练习,我尝试使用 jQuery 在一系列 div 中查看更多/更少的内容。我创建了按钮来触发“查看更多”和“查看更少”事件,同时在展开 div 时隐藏“查看更多”按钮,或者在缩小 div 时隐藏“查看更少”按钮。
我的问题是,当用户单击按钮时,它会更改页面上的所有按钮,而不是该特定 div 内的按钮。
我尝试了几种不同的方法来解决这个问题,但没有成功。我有点了解如何使用 $(this) 以及如何遍历元素...但我无法解决这个问题。
这是我正在使用的 jQuery ->
//hide "see less" button
$(".less-button").hide();
//capture click on more button
//add class to enlarge div
$(".more-button").click(function(){
$(this).parent().addClass("more");
//hide "see more" button
$(".more-button").hide();
//show "see less" button
$(".less-button").show();
});
//capture click on less button
//remove class to shrink div
$(".less-button").click(function(){
$(this).parent().removeClass("more");
//hide "see less" button again
$(".less-button").hide();
//show "see more" button... again
$(".more-button").show();
});
这是我的页面代码笔的链接-> http://codepen.io/seanpierce/pen/vNeVJm/
任何帮助将不胜感激!
最佳答案
在偶数处理程序中,查找同级按钮: http://codepen.io/anon/pen/BowGJg
//hide "see less" button
$(".less-button").hide();
//capture click on more button
//add class to enlarge div
$(".more-button").click(function(){
$(this).parent().addClass("more");
//hide "see more" button
$(this).hide();
//show "see less" button
$(this).siblings(".less-button").show();
});
//capture click on less button
//remove class to shrink div
$(".less-button").click(function(){
$(this).parent().removeClass("more");
//hide "see less" button again
$(this).hide();
//show "see more" button... again
$(this).siblings(".more-button").show();
});
关于javascript - 使用 JQuery 仅在该 div 中显示/隐藏按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33154792/