2012-06-24 28 views
3

我想計算寬度和div的寬度和頁面中同一div類多次出現的文本之間的差異。jQuery .each()獲取多個div的值

的HTML:

<div class="post_content"> 
     <div class="container"> 
      <div class="title-holder"> 
      <h2><a href="link.html" class="widget-title">Crossword Book</a></h2> 
      </div> 
     </div> 

     <div class="container"> 
     <div class="title-holder"> 
     <h2><a href="link.html" class="widget-title">Crossword Bookstore Ltd. &ndash; Elgin Road</a></h2> 
     </div> 
     </div> 
</div> 

的CSS:

div.container{ 
    width: 130px; 
} 
div.title-holder { 
    width: 130px; 
    height:20px; 
    text-align:center; 
    background: silver; 
    overflow:hidden; 
    position: relative; 
} 
div.title-holder a { 
    position: relative; 
    white-space:nowrap; 
    left: 0px; 
} 
div.image{ 
    background: brown; 
    width: 100%; 
    height: 100px; 
} 

下面的腳本正確地輸出第一div的結果,然後重複相同的結果。它不會去下一個div並給出下一個結果。

$("div.title-holder").each(function(){  
    var m = $(this).width(); 
    var n = $("div.title-holder h2 a.widget-title").width(); 
    var o = m - n; 

    alert ("title: " + m + " text: " + n + " diff: " + o);  

}); 

輸出是

First Alert: title: 130 text: 108 diff: 22 
Second Alert: title: 130 text: 108 diff: 22 

我所期待實現的是

First Alert: title: 130 text: 108 diff: 22 
Second Alert: title: 130 text: 258 diff: -128 

回答

7

的價值:

var n = $("div.title-holder h2 a.widget-title").width(); 

將始終是相同的(該選擇器查詢的第一個結果)。你需要做的:

var n = $(this).find("a.widget-title").width(); 

或更具體:

var n = $("div.title-holder").children("h2").children("a.widget-title").width(); 
+0

感謝您的解釋。我錯過了明顯的。 :) – Ranadeep

+0

在後一種情況下,你可以說「div.title-holder> h2> a.widget-title」,這更簡單。 –

2

使用這樣的:

var n = $(this).find("h2 a.widget-title").width(); 
0

jsBin demo

$("div.title-holder").each(function(){  
    var m = $(this).width(); 
    var n = $("h2 a.widget-title", this).width(); 
    var o = m - n; 

    alert("title: " + m + " text: " + n + " diff: " + o);  

});