开发者

reflection in javascript/jQuery

I have a json object;

a.Name = "John";
a.Nick = "Smith";
a.Info = "hi there";

and some html like this:

<input id="Name" />
<input id="Nick" />
<input id="Info" />

is it possible to automatically set the values 开发者_如何学Pythonof these inputs according the object's property names ?

What I'd like to do is to loop through the object's properties and look for an input with same id and set it's value.


Since IDs should be unique anyway, here’s a more efficient solution:

$.each(a, function(k, v) {
  $('#' + k).val(v);
});

Of course, this is even faster:

$.each(a, function(k, v) {
  (document.getElementById(k) || {}).value = v;
});

If you prefer not to use jQuery at all, you could do it like this:

for (var i in a) {
  (document.getElementById(i) || {}).value = a[i];
});

Edit: Updated the last two answers, since OP mentioned that some inputs might not exist.


You want to do this?

$.each(a, function(k,v) {
    $('input[id='+k+']').val(v);
})


try this:

for (var prop in a) { 
  alert(propertyName + ' => ' + a[propertyName]); 
}

this version don't need jQuery ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜