开发者

filling javascript object "on the fly"

开发者 https://www.devze.com 2023-01-27 21:35 出处:网络
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:

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

精彩评论

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