我正在尝试获取存储在每个帖子的post-content
容器中的图像数量。
帖子的布局如下:
<div class="post">
<div class="post-toolbar">
<div class="post-date">date</div>
<div class="signs">
<div class="hearts">♥</div>
<div><img src="logo.png"></div>
<div><img src="logo2.png"></div>
</div>
<div class="post-title">title</div>
</div>
<div class="post-content">
<a href="#link"><img src="image.png"></a>
<a href="#link"><img src="image.png"></a>
</div>
</div>
一个看起来像这样的Javascript片段:
$('.hearts').live("click",function() {
var amount = $(this).parent().parent().parent().find("img").size();
console.log(amount);
});
目前amount
的值为4
。
我确信使用jQuery访问.post-content
div是一种更好的方法。
答案 0 :(得分:2)
$(this).parents(".post")
怎么样?
$('.hearts').live("click",function() {
var amount = $(this).parents(".post").children(".post-content").find("img").size();
alert(amount);
});
答案 1 :(得分:2)
$('.hearts').live("click",function() {
var post = $(this).closest('.post'); // will find the first element with the class post up the DOM tree
var amount = $('.post-content img', post).size();
console.log(amount);
});
顺便说一下,你应该真正调查.delegate()
,再也不要再使用.live()
了,因为直播是way slower而不是委托。
如果您使用的是{jQuery 1.7或更高版本,请使用.on()
。