2

假设我有以下内容:

var address = {id: 100, name: "Gregg", addressOne: "111 1st Street"};

和一个 HTML 表单:

<input id="name" />
<input id="addressOne" />

我想知道是否有一种方法可以遍历表单的所有 INPUT 元素,并根据 JSON 对象的属性设置它们的值。以下是我可以采取的长期方法:

$.each($("input"), function(idx, input) {
   if (input.attr("id") == "name") input.val( address.name );
   if (input.attr("id") == "addressOne") input.val( address.addressOne );
});

我想知道是否有办法在没有 IF 语句的情况下执行上述操作。JavaScript中是否有某种方法可以将两者动态映射在一起。我希望这是有道理的。

4

6 回答 6

5

您可以使用val方法:

$('input').val(function(i, v){
    return address[this.id]
})

http://jsfiddle.net/GKUMk/

于 2012-10-04T21:48:48.023 回答
1
$("#name").val(address.name);
$("#addressOne").val(address.addressOne);
于 2012-10-04T21:47:35.920 回答
0
$.each($("input"), function(idx, input) {
   if (address[input.attr("id")]) {
       address[input.attr("id")]
   }
});
于 2012-10-04T21:46:53.843 回答
0

你可以试试这个

$('input').each(function(){
    $(this).val(address[this.id]);
});

演示

于 2012-10-04T21:48:36.277 回答
0

I think that this would work, but I redefine the var address to a JSON object.

var address = {id: 100, name: "Gregg", addressOne: "111 1st Street"}

And the iterator could be:

$.each($("input"), function(idx, input) {
    $(this).val( address[input.id] );
});​

I hope this helps.

于 2012-10-04T21:56:43.170 回答
0
<input type="text" id="name" />
<input type="text" id="addressOne" />

var address = { id: 100, name: "Gregg", addressOne: "111 1st Street" },
prop, $field;

for ( prop in address ) {
    $( "#" + prop ).val( address[prop] );
}

Note the address variable is now an object literal rather than an array.

Fiddle: http://jsfiddle.net/kboucher/Gt9ND/

于 2012-10-04T21:58:51.920 回答