我想循环 HTML 表单的元素,并将 <input> 字段的值存储在对象中。但下面的代码不起作用:
function config() {
$("#frmMain").children().map(function() {
var child = $("this");
if (child.is(":checkbox"))
this[child.attr("name")] = child.attr("checked");
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
return null;
});
以下内容也不会(受到 jobscry 答案的启发):
function config() {
$("#frmMain").children().each(function() {
var child = $("this");
alert(child.length);
if (child.is(":checkbox")) {
this[child.attr("name")] = child.attr("checked");
}
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
});
}
警报始终显示child.length == 0
。手动选择元素有效:
>>> $("#frmMain").children() Object length=42 >>> $("#frmMain").children().filter(":checkbox") Object length=3
关于如何正确执行循环的任何提示?
最佳答案
认为您不需要引用此内容:
var child = $("this");
尝试:
var child = $(this);
关于javascript - jQuery 中的循环元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/170180/