javascript - 使用 JQuery 仅在该 div 中显示/隐藏按钮

标签 javascript jquery html hide show

作为练习,我尝试使用 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/

相关文章:

javascript - 您如何按字母顺序对段落标签或 TD 标签(例如)进行排序?

javascript - 相同 CSS 动画的不同动画持续时间

html - 如何将这些 div 的图像垂直居中?

javascript - Angular ng-repeat 内的动态属性引用

javascript - 如何在 PHP Laravel 中为货币值设置自动数字 jquery?

javascript - 无法比较 JavaScript 中的两个字符串

html - 使用 Excel 从 Lotus Notes 发送电子邮件并具有附件和 HTML 正文

javascript - 单击弹出窗口外部时关闭弹出的小框

javascript - Aurelia 简单绑定(bind)不起作用

javascript - 如何对 AJAX 返回的元素执行 Jquery?