将JSON属性映射到HTML ID以轻松设置值

Gre*_*egg 2 javascript jquery json

假设我有以下内容:

var address = {id: 100, name: "Gregg", addressOne: "111 1st Street"};
Run Code Online (Sandbox Code Playgroud)

还有一个HTML表单:

<input id="name" />
<input id="addressOne" />
Run Code Online (Sandbox Code Playgroud)

我想知道是否有一种方法来迭代表单的所有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 );
});
Run Code Online (Sandbox Code Playgroud)

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

und*_*ned 5

你可以使用val方法:

$('input').val(function(i, v){
    return address[this.id]
})
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/GKUMk/