jQuery:当它们共享相同的CSS类时,如何定位被点击的元素? [英] jQuery: How do I target the clicked element when they all share the same CSS class?
问题描述
我的页面上有3个div元素,每个元素都有相同的CSS类.shape
I have 3 div elements on my page and each of them has a same CSS class ".shape"
在我的JS中,我想定位当前的点击.shape以便使用jQuery slideDown过渡将一些额外的html插入到.shape的底部。
Within my JS, I want to target the current click ".shape" so that some extra html will get inserted to the bottom of the ".shape" with a jQuery slideDown transition.
当你点击。塑造再次,额外的HTML将滑动。
And when you click on the ".shape" again, the extra html will slideUp.
我如何以简单的方式做到这一点?
我有什么:
How do I do that in an easy way? What I have:
$(".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>
我也不知道如何添加切换+滑动效果。
I also have no idea how to add in the toggle + sliding effect.
编辑:
解决方案
http:// codepen.io/vennsoh/pen/rVjeQy
不确定我编写JS的方式是否是最优雅的方法。
Not sure if the way I wrote my JS is the most elegant approach.
推荐答案
定位点击的元素 $(this)
$(".shape").click(function() {
var clickedShape = $(this);
});
一旦你有 $(this)
,您可以使用 find()
。
Once you have $(this)
, you can target elements inside of it with find()
.
或者就HTML而言,使用 next()在你的形状后找到揭密元素。
Or in the case of your HTML, use next() to locate the reveal element after your shape.
找到合适的元素后,你可以 slideUp()
, slideDown()
或 slideToggle()
。
Once you have found the proper element, you can slideUp()
, slideDown()
, or slideToggle()
.
$(".shape").click(function() {
var revealThing = $(this).next();
revealThing.slideToggle();
});
http://jsfiddle.net/yopp6L22/1/
这篇关于jQuery:当它们共享相同的CSS类时,如何定位被点击的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!