jQuery每次循环两次,为什么?

时间:2011-11-24 16:35:24

标签: jquery loops

我有一个脚本设置,循环代码就像html结构一样

http://jsfiddle.net/OwenMelbz/mPVbE/

它基本上搜索li的非空id并将它们放入csv字符串。

然而无论何时我运行它总是在我的非小提琴版本中添加一个额外的循环,所以我有,9 li,3包含ID,循环运行4次。这是为什么?

在我的非开发版本中,它实际上再次选择第一个li的ID并添加它。例如。

1,2,3,4,5,6,1

1将在第一个元素上。不明白为什么会这样做?

感谢

3 个答案:

答案 0 :(得分:3)

这是一个更新,更简单的版本:

$("#ingredients").submit(function(event) {
    event.preventDefault(); //Just for testing so the form doesn't submit
    var params = []; //Array of params
    $("li").each(function() {
        if ($(this).prop("id") != "") //Prop always returns a string, empty if no ID
            params.push($(this).prop("id")); //Push the ID into the array
    });
    alert(params.join(",")); //Join the array with a coma
});

http://jsfiddle.net/mPVbE/4/

答案 1 :(得分:1)

您的代码中alert(params);之后还有.each()个额外费用。这是最后一个alert()

的责任

答案 2 :(得分:1)

小提琴示例中.each()循环外面有一个警告。

我更新它:     http://jsfiddle.net/IrvinDominin/mPVbE/3/

你的非小提琴代码中的

可能是同样的问题吗?

相关问题