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() オブジェクトの長さ=42 >>> $("#frmMain").children().filter(":checkbox") オブジェクトの長さ=3
ループを正しく行うためのヒントはありますか?
ベストアンサー1
これについては引用符は必要ないと思います:
var child = $("this");
試す:
var child = $(this);