2012-01-02 34 views
3

我試圖獲取存儲在每個帖子的post-content容器中的圖像數量。獲取特定div中的圖像數量

後的佈局是這樣的:

<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> 

而且一段JavaScript代碼,它看起來像這樣:

$('.hearts').live("click",function() { 
    var amount = $(this).parent().parent().parent().find("img").size(); 
    console.log(amount);   
}); 

目前的amount值是4

我敢肯定這是一個更好的方式來訪問與jQuery .post-content股利。

+0

$(「img」,「div.post-content」)可能會有幫助。 jQuery讓你有機會使用上下文(第二參數)來搜索你的內容(第一個參數)。 – microspino 2012-01-02 03:16:46

+0

@microspino將獲得所有'後內容'div的圖像,而不是每個帖子。 – PeeHaa 2012-01-02 03:18:51

回答

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);   
}); 

BTW,你真的應該考慮.delegate()永不再使用.live()因爲住的是way slower比委託。

甚至更​​好,如果你在jQuery 1.7或更高版本使用.on()

+0

中的圖片數量非常棒!謝謝 – Backslash 2012-01-02 03:22:18

+0

另一個小的性能改進是使用length而不是size()方法。摘自文檔:.size()方法在功能上等同於.length屬性;然而,.length屬性是首選的,因爲它沒有函數調用的開銷。文檔網址:http://api.jquery.com/size/ – 2012-01-02 04:02:03

2

$(this).parents(".post")怎麼樣?

$('.hearts').live("click",function() { 
    var amount = $(this).parents(".post").children(".post-content").find("img").size(); 
    alert(amount);  
}); 
+0

看起來更好!但是我*金額*的價值仍然是4.我只想要* post-content * – Backslash 2012-01-02 03:18:26