我的页面上有 3 个 div 元素,每个元素都有相同的 CSS 类“.shape”
在我的 JS 中,我想定位当前点击“.shape”,以便通过 jQuery slideDown 转换将一些额外的 html 插入到“.shape”的底部。
当您再次单击“.shape”时,多余的 html 将向上滑动。
如何以简单的方式做到这一点? 我有什么:
$(".shape").click(function() {
var id = $(this).attr("id");
var selected = id + "-reveal";
});
在我的 HTML 中,
<div class="shape" id="shape1">Content</div>
<div class="hidden" id="shape1-reveal">Content</div>
<div class="shape" id="shape2">Content</div>
<div class="hidden" id="shape2-reveal">Content</div>
<div class="shape" id="shape3">Content</div>
<div class="hidden" id="shape3-reveal">Content</div>
我也不知道如何添加切换+滑动效果。
编辑: 解决方案 http://codepen.io/vennsoh/pen/rVjeQy
不确定我编写 JS 的方式是否是最优雅的方式。
最佳答案
使用 $(this)
定位点击的元素
$(".shape").click(function() {
var clickedShape = $(this);
});
一旦你有了$(this)
,你就可以用find()
定位其中的元素。 .
或者对于您的 HTML,使用 next()在您的形状之后找到显示元素。
找到合适的元素后,您可以 slideUp()
, slideDown()
, 或 slideToggle()
.
例子
$(".shape").click(function() {
var revealThing = $(this).next();
revealThing.slideToggle();
});
关于javascript - jQuery:当点击的元素都共享相同的 CSS 类时,我如何定位它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30518257/