如何在父级内部调用父元素?
例如,我在页面上有多个这些
<div class="parent">
<div class="some-text">text</div>
<div class="some-image">image</div>
<div class="some-btn">btn</div>
</div>
<div class="parent">
<div class="some-text">text</div>
<div class="some-image">image</div>
<div class="some-btn">btn</div>
</div>
<div class="parent">
<div class="some-text">text</div>
<div class="some-image">image</div>
<div class="some-btn">btn</div>
</div>
当我点击.some-btn时,我只想知道那个.parent元素,其中.some-btn是一个孩子/点击。
我的jquery现在看起来像这样
$(".some-btn").click(function() {
$(".some-text").toggleClass("active",1000,"easeInOutQuad");
$(".some-image").toggleClass("active",1000,"easeInOutQuad");
$(".some-btn").toggleClass("active");
})
但这当然会激活所有.parent元素。
答案 0 :(得分:2)
选择单击元素的父元素,然后在此元素内选择:
$(".some-btn").click(function() {
var that = $(this);
var par = that.closest('.parent');
par.find(".some-text").toggleClass("active",1000,"easeInOutQuad");
par.find(".some-image").toggleClass("active",1000,"easeInOutQuad");
that.toggleClass("active");
})
答案 1 :(得分:0)
您需要遍历最近的父div,然后在其中找到元素:
$(".some-btn").click(function() {
var _this = $(this);
var closestparent = _this.closest('.parent')
closestparent.find(".some-text,.some-image").toggleClass("active",1000,"easeInOutQuad");
_this.toggleClass("active");
});
$(".some-btn").click(function() {
var _this = $(this);
var closestparent = _this.closest('.parent')
closestparent.find(".some-text,.some-image").toggleClass("active",1000,"easeInOutQuad");
_this.toggleClass("active");
});
&#13;
.active{
color:red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="parent">
<div class="some-text">text</div>
<div class="some-image">image</div>
<div class="some-btn">btn</div>
</div>
<div class="parent">
<div class="some-text">text</div>
<div class="some-image">image</div>
<div class="some-btn">btn</div>
</div>
<div class="parent">
<div class="some-text">text</div>
<div class="some-image">image</div>
<div class="some-btn">btn</div>
</div>
&#13;