3

我正在尝试计算 div 的宽度和同一 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
4

3 回答 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();
于 2012-06-24T18:08:13.790 回答
2

像这样使用:

var n = $(this).find("h2 a.widget-title").width();
于 2012-06-24T18:07:31.983 回答
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);    

}); 
于 2012-06-24T18:17:10.100 回答