Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取特定div中的图像数量_Javascript_Jquery_This_Image - Fatal编程技术网

Javascript 获取特定div中的图像数量

Javascript 获取特定div中的图像数量,javascript,jquery,this,image,Javascript,Jquery,This,Image,我试图获取每个帖子的post content容器中存储的图像量 帖子的布局如下所示: <div class="post"> <div class="post-toolbar"> <div class="post-date">date</div> <div class="signs"> <div class="hearts">&hearts;</div> <

我试图获取每个帖子的
post content
容器中存储的图像量

帖子的布局如下所示:

<div class="post">
  <div class="post-toolbar">
    <div class="post-date">date</div>
    <div class="signs">
      <div class="hearts">&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>
$('.hearts').live("click",function() {
    var amount = $(this).parent().parent().parent().find("img").size();
    console.log(amount);        
});
此时,
amount
的值为
4

我相信使用jQuery访问
.post content
div是一种更好的方法

那么
$(这个)家长(“.post”)

顺便说一句,你应该认真研究一下,不要再使用
.live()
,因为live比delegate更重要


如果您使用的是jQuery 1.7或更高版本,那么使用
.on()

$(“img”、“div.post-content”)可能会有所帮助。jQuery让您有机会使用上下文(第二个参数)来搜索内容(第一个参数)。@microspino将获得所有
帖子内容的图像,而不是每个帖子的图像。看起来更好!但我认为金额的值仍然是4。我只想得到post content中的图像数量另一个小小的性能改进是使用length而不是size()方法。文档摘录:.size()方法在功能上等同于.length属性;但是,.length属性是首选的,因为它没有函数调用的开销。文档URL:
$('.hearts').live("click",function() {
    var amount = $(this).parents(".post").children(".post-content").find("img").size();
    alert(amount);       
});
$('.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);        
});