Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取内部元素的宽度,并使用它设置外部元素的宽度_Javascript_Jquery_Html - Fatal编程技术网

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

Javascript 获取内部元素的宽度,并使用它设置外部元素的宽度,javascript,jquery,html,Javascript,Jquery,Html,我有这个密码。但它不起作用。我需要设置全部的总宽度,然后将其用于包装div 将您的代码更改为 var totalWidth = 0; $('#breadcrumb-wrapper a').each(function(index, el) { totalWidth = totalWidth + $(this).width(); }); $('#breadcrumb-wrapper > div').width(totalWidth); 像这样更新脚本 var totalWidth

我有这个密码。但它不起作用。我需要设置全部的总宽度,然后将其用于包装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);
检查更新的JSFIDLE


工作功能如下所示:

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,因此在循环范围内声明不同的变量。

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

$('#breadcrumb-wrapper > div').width(totalWidth);