使用jQuery .each()获取多个div的值

3

我将尝试计算一个页面中多次出现相同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

What I am looking to achieve is

First Alert: title: 130 text: 108 diff: 22
Second Alert: title: 130 text: 258 diff: -128
3个回答

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

谢谢解释。我忽略了显而易见的东西。 :) - Ranadeep
在后一种情况下,您可以说“div.title-holder > h2 > a.widget-title”,这更简单。 - Mo Valipour

2

使用方法如下:

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

0

jsBin演示

$("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);    

}); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接