在以下场景中,当我点击readMore链接时如何获得data-kush
的值?
还有更多的产品以相同的方式显示,我需要显示在点击的readMore链接上方的data-kush的值。
<div>
<div class="product itemName" data-kush="9a7e96cb9b72fb8c526961e7366bf1a8">
Norwegian Kush
</div>
<div class="moreInfo">
<span class="readMore">Click to read more...</span>
</div>
</div>
<div>
<div class="product itemName" data-kush="fb8c526961e7366bf1a8">
Bubba Kush
</div>
<div class="moreInfo">
<span class="readMore">Click to read more...</span>
</div>
</div>
的jQuery
$('.readMore').click(function() {
alert($(this).closest('.itemName').data('kush'));
});
以上是我认为可行的,但没有。你能帮忙吗?
答案 0 :(得分:2)
它是当前元素父级的前一个兄弟。
所以
$('.readMore').click(function() {
alert($(this).parent().prev('.itemName').data('kush'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<div class="product itemName" data-kush="9a7e96cb9b72fb8c526961e7366bf1a8">
Norwegian Kush
</div>
<div class="moreInfo">
<span class="readMore">Click to read more...</span>
</div>
</div>
<div>
<div class="product itemName" data-kush="fb8c526961e7366bf1a8">
Bubba Kush
</div>
<div class="moreInfo">
<span class="readMore">Click to read more...</span>
</div>
</div>
.closest()用于获取祖先元素,因为目标元素不是祖先,它将不起作用
答案 1 :(得分:0)