开发者

Problem with big amount of dom elements

I have problem with DOM elements I need to add 2000 blocks. I try to do this by setTimeout, but then events not working with this elements. Anyone what mistake I have made?

function init(){ 
    $('#regions').prepend("<ul></ul>"); 
    setTimeout(function(){ 
        var opt=$('#regions ul'); 
        for(var i=0; i<50; ++i){ 
            for(var j=0; j<50; ++j) 
                opt.append('<li class=\"field\"></li>'); 
        } 
开发者_Python百科    }, 0); 
} 


Build first the full HTML that you want to insert and then do it in a single operation.

function init(){ 
    var html =[];
    for(var i=0; i<50; ++i){
       for(var j=0; j<50; ++j)
           html.push('<li class=\"field\"></li>');
    } 

    $('#regions').prepend("<ul>" + html.join('') + "</ul>"); 
} 


You can use jQuery's live method. With its help you can bind event to set of elements even though they might be added later.

For example:

$('#regions ul li').live('mouseover', function() {
  // Live handler called.
});

See more info here: http://api.jquery.com/live/


since you are using jquery, by loading elements in after page load you need to "live" the event to the elements.

Edit: //i said bind but thought of live,

lets say that all elements has a class called "added", just to make things more simple.

then you would bind the hover event by doing:

$(".added").live("mouseover",function(){
//do stuff
});


Some quick stuff:

  1. Why do you have double the for loop instead of just 1?
  2. You should take a look at AlfonsoML's suggestion of building the whole HTML string first, then inserting it into the DOM.
  3. Much as live is really convenient, I most always suggest using delegate instead. Something like $('#regions').delegate('li','click', function (e) { ... }) does the same thing as live, and is much cleaner on the DOM.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜