获取内部元素的宽度并使用它来设置外部元素的宽度

Get a width of inner elemets and use it to set a width of outer element

本文关键字:元素 设置 外部 内部 获取      更新时间:2023-09-26

我有这个代码。但这行不通。我需要设置所有的总宽度,然后用它来换行div。http://jsfiddle.net/8jPcP/

<div id="breadcrumb-wrapper">
   <div>
   <a href="">asd</a>
   <a href="">asd</a>
   <a href="">asd</a>
   <a href="">asd</a>
   <a href="">asd</a>
   </div>
</div>

将代码改为

var totalWidth = 0;
$('#breadcrumb-wrapper a').each(function(index, el) {
   totalWidth = totalWidth + $(this).width();
}); 
$('#breadcrumb-wrapper > div').width(totalWidth);

像这样更新你的脚本

 var totalWidth = 0;
$('#breadcrumb-wrapper a').each(function() {
    totalWidth = totalWidth + $(this).width();
   /* alert(totalWidth);*/
});
    $('#breadcrumb-wrapper > div').width(totalWidth);

查看已更新的jsfiddle

http://jsfiddle.net/8jPcP/1/

工作函数是这样的:

var totalWidth = 0;
$('#breadcrumb-wrapper a').each(function(index, el) {
    var newWidth = totalWidth + $(this).width();
    totalWidth = newWidth;
});
$('#breadcrumb-wrapper > div').width(totalWidth);

你在循环中使用var newWidth设置newWidth,因此在循环范围内声明了一个不同的变量