简体   繁体   中英

adding newly created dom elements to an empty jQuery object

Why doesn't this work in jQuery 1.4.2?


var $list = $([]);
for(var i=0; i<50; i++) {
    $list.add( $('<div/>', { id: 'jake', class: 'test' }).data('test', { hi: 'hello' }) );
}
alert($list.size()); // 0

Thanks!

Pointing back the reference list again works for me; eg $list = $list.add( $('<div/>') ) ;

var $list = $([]);
for(var i=0; i<50; i++) {
    $list=$list.add( $('<div/>', { 'id': 'jake'+i, 'class': 'test' }).data('test', { hi: 'hello' }) );
}
alert($list.size()); // 50

为什么不add不起作用,我不知道,但是由于jQuery是类似Array的对象,因此您可以将其替换为push ,这应该可以完成您想要的操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM