开发者

filling javascript object "on the fly"

HI, i have an object: var myobject = new Object; and i want to dynamically fill it wit开发者_运维技巧h properties while looping through jquery input collection in that manner:

$('.test').each(function(){
    myobject.$(this).attr('name') = $(this).val();
});

what i'm doing wrong here? thanks in advance


Try this:

$('.test').each(function () {
    var e = $(this);
    myobject[e.attr('name')] = e.val();
});

Objects in JavaScript can be accessed using object.property or object['property'] (these two are equivalent). The latter allows you to use expressions (like variables): object[propertyName].


With the way you are doing it:

var myObject = {};
$('.test').each(
    function(){
        var elem = $(this);
        myObject[elem.attr('name')] = elem.val();
    }
);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜