mat*_*att 7 jquery jquery-selectors closest
我有:
<ul class="rating">
<h3>Like this</h3>
<li class="rating-number">
<div id="iLikeThis" class="iLikeThis">
<span class="counter">2</span>
</div>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
这是我的jquery代码
$('.iLikeThis .counter').each(function() {
$(this).parent().parent().parent().children('h3').text('You like this');
$(this).parent().addClass('like');
});
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来选择最近的h3元素.它确实可以使用3次parent()但不能使用最接近的('h3).
为什么?
Bol*_*ock 14
由于h3
不是父母.counter
,这是行不通的.使用.closest()
上.rating
,而不是找到它h3
:
$(this).closest('.rating').children('h3').text('You like this');
Run Code Online (Sandbox Code Playgroud)