【问题标题】:Undefined item in each loop每个循环中的未定义项
【发布时间】:2014-09-03 17:53:44
【问题描述】:

下面的代码有一个 jquery 每个语句都经过一个包含 h1,h2 h3,h4 的 div.faq。根据我的逻辑(现在我失败了),应该通过 div 运行的代码选择所有 Header 元素,然后将 h1/h2 设为列表项,将 h3/h4 设为子列表项。出于某种原因,在每个子列表开始之前,我不断得到一个“未定义”元素。

//Declare everything
var sidebar = "";
var sidebar_header = new Array();
var sidebar_items = new Array();
var i = 0;

//Select all elements
$(".faq h3,.faq h4,.faq h1,.faq h2").each(function(index, value){

    // Add an ID to each element
    $(this).attr("id", "item-" + index);

    //If element is h1 or element is h2
    if($(this).is("h1") || $(this).is("h2")){

        sidebar_header[i] = "<li><a href='#item-" + index + "'>" + $(this).text() + "</a>";

        i++;
    //If element is h3 or is h4
    }else if($(this).is("h3") || $(this).is("h4")){

        sidebar_items[i - 1] += "<li><a href='#item-" + index + "'>" + $(this).text() +" </a></li>";

    }


});


var total = i;

//Loop through all list items and add sub list items
for(i=0;i<total;i++){

    sidebar += sidebar_header[i] + "<ul>" + sidebar_items[i] + "</ul></li>";

}

//Append
$(".side").append("<ul>" + sidebar + "</ul>");

一切都“有效”,除了我的结果是:

List item 1
 - Undefined
 - Sub List item 1
 - Sub List item 2
 - Sub List item 3

List item 2
 - Undefined
 - Sub List item 1
 - Sub List item 2

我不知道什么是未定义的。一切都被宣布了。我只是将项目添加到已定义的数组中。我在代码的不同部分运行了几个 console.log,问题似乎在这里:

sidebar_items[i - 1] += "<li><a href='#item-" + index + "'>" + $(this).text() +" </a></li>";

但我不知道为什么。欢迎提出建议!

更新:

示例链接:http://jsfiddle.net/pgw47ecb/

【问题讨论】:

  • 请给一个jsfiddle工作。需要 HTML 来重现案例并确定失败。
  • 您能否在循环正文中添加console.log(this) 并发布它记录的内容?

标签: javascript jquery loops undefined each


【解决方案1】:

您将一个字符串连接到一个没有值的数组索引上(嗯,它的值是undefined)。 Javascript 很高兴将 undefined 转换为字符串并进行连接,因此当您第一次尝试将新 HTML 添加到该索引时,您会得到 "undefined" + '&lt;li&gt;...&lt;/li&gt;'

您需要先将sidebar_items 的每个索引初始化为一个空字符串(如果未定义该索引的值,则不使用字符串连接)。

$(".faq h3,.faq h4,.faq h1,.faq h2").each(function(index, value){

// Add an ID to each element
$(this).attr("id", "item-" + index);

//If element is h1 or element is h2
if($(this).is("h1") || $(this).is("h2")){

    sidebar_header[i] = "<li><a href='#item-" + index + "'>" + $(this).text() + "</a>";

    i++;
//If element is h3 or is h4
}else if($(this).is("h3") || $(this).is("h4")){
    // Give this index a value: an empty string.
    if(typeof sidebar_items[i - 1] !== "string") sidebar_items[i - 1] = "";

     sidebar_items[i - 1] += "<li><a href='#item-" + index + "'>" + $(this).text() +" </a></li>";

}


});

【讨论】:

  • 这解决了它。我以为我在连接数组内的值,而不是数组本身。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 2017-04-21
  • 2021-03-24
相关资源
最近更新 更多