jquery 数组返回一个未定义的?

标签 jquery arrays undefined each

我试图从这个 html 代码中获取一个数组,以将框(其 id 中包含数字)添加到我的内容中:

<a href="#" data-box="38,39,40">An Array</a>

要添加的框:

<div id="box38">
    ...
</div>
<div id="box39">
    ...
</div>
<div id="box40">
    ...
</div>

因为还有这样的 html 行:

<a href="#" data-box="24">No Array</a>

我还需要一些东西来检测是否有多个值或只有一个值。在本例中,我只使用了 if (theid.length > 2) 因为单个值不会超过两个字符。

数组应该是[38,39,49],而且确实如此,因为console.log(theid);返回的是这个数组。

var theid = $(this).data('box');
var newHTML = '';

if (theid.length > 2) {
    theid = theid.split(',');
    $.each(theid, function(idx) {
        newHTML += $('#box' + theid[idx]).html();
    });
} else {
    var newHTML = '';
    newHTML = $('#box' + theid).html();
    console.log(theid);
};

但是如果我随后将 newHTML 添加到现有内容 content.html(newHTML); 加载的框前面总是有一个“未定义”?这是屏幕截图:

enter image description here

最佳答案

这是变量提升的副产品。由于您使用的是 += 运算符,因此该字符串将被附加到之前 undefined variable newHTML 的末尾。你可以这样看:

//hoisted
var newHTML = undefined;

var theid = $(this).data('box');

if (theid.length > 2) {
 theid = theid.split(',');
 $.each(theid, function(idx) {
    newHTML += $('#box' + theid[idx]).html();
 });
} else {
 /*var */newHTML = '';
 newHTML = $('#box' + theid).html();
 console.log(theid);
};

关于jquery 数组返回一个未定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24403911/

相关文章:

php - PHP包含文件中的 undefined variable 错误

javascript - 如何将日期选择器包装在新的 div 中?

javascript - IE 9、10、11 - Ajax 调用不返回

arrays - 如何打印包含类的数组的内容以及如何在 Swift 中访问数组的某些值

arrays - 返回数组中重复的元素

javascript - 在关联数组上的 for in 迭代的控制台输出末尾未定义,JavaScript?

javascript - jQuery slider 在 IE 中不起作用

javascript - 仅附加第一个元素

java - For 循环遍历字符串并添加/替换字符

c - 从共享库切换到 dll,现在出现找不到 pow() 的错误