2

我正在努力以一种形式遍历所有值,但我一直没有定义,然后我的值就出现了。我正在动态创建表单,所以我认为未定义的可能来自空白字段。

这是我用来获取所有元素的代码:

//try to get all elements
var output;
$(this).parents('form') // For each element, pick the ancestor that's a form tag.
.find(':input') // Find all the input elements under those.
.each(function(i) {
    //alert(this.value+ " = " + i);
    if (typeof this.value === "undefined") {
        output = "nothing here";
    } else {
        output += this.value;
    }
});
$("div#total").append("value = " + output + "<br>");

如果我输入 1,2,3,4,5,6 那么我的输出是:

hello value = undefined
value = undefined1
value = undefined1
value = undefined12
value = undefined12
value = undefined123
value = undefined123
value = undefined1234
value = undefined1234
value = undefined12345
value = undefined12345
value = undefined123456

结果是我想要的,除了未定义的部分。我看到了这个答案:JavaScript: undefined !== undefined? 并尝试了他们的建议,但如果值不是未定义的,我似乎无法让我的程序保存该值。

如果它有帮助,这里是完整的代码:http: //jsfiddle.net/lostsoul/rKLrZ/

4

2 回答 2

3

初始化output为空字符串。

var output = "";

如果 aninput没有值,它会给你一个空字符串而不是undefined.

于 2012-07-13T03:48:33.033 回答
0

未初始化的 varoutput实际上有一个值undefined

变量输出;// 输出值未定义
输出+=“2”;// 未定义 + "2" -> "未定义2"
于 2012-07-13T04:00:22.613 回答