使用JQuery每个函数返回元素宽度

时间:2015-02-02 23:42:33

标签: javascript jquery html css

我目前有ul,大约有20 li。每个li的结构如下:

 <li class="block">
  <a href="#">
    <div class="front">
      <img src="..." />
    </div>
    <div class="back">
     <p>Text</p>
    </div>  
  </a>
</li>   

我想浏览每个li.block,查找其宽度,并将锚标记的宽度设置为等于此数字。

这是我现在使用的功能,但它不起作用:

$(document).ready(function() {
  var $currentWidth = $("li.block").width();
  $( "li.block a" ).css( "width", $currentWidth);
});

使用.each()和类似上述代码的正确方法是什么来解决我的问题?

2 个答案:

答案 0 :(得分:1)

循环使用每个块

$("li.block").each(function() {//stuff});

在该功能中,您可以使用this

获取相关的阻止
var width = $(this).width();

然后,您可以将其应用于该块内的链接:

$(this).children('a').css("width", $currentWidth);

当然,如果你的html总是那样,那可能会有所不同 - 使用适当的选择器。

所以把它们放在一起,你会有这样的东西:

$("li.block").each(funtion() {
  var width = $(this).width();
  $(this).children('a').css("width", $currentWidth);
});

答案 1 :(得分:0)

怎么样:

$('#your-ul').find('li.block').each(function(){
  // inside here, 'this' refers to to a specific 'li.block' element
  $(this).find('a').width( $(this).width() );
});

虽然我有点怀疑为什么这些宽度不一样。