I have an array of jQuery objects that I built and which have events attached to them.
var obs = [];
for(var i=0;i<100;i++) {
var j =开发者_JS百科 jQuery('<div></div>');
j.click(function() { console.log('Clicked ' + i); });
obs.push(j);
}
My HTML is:
<div id="replaceme"></div>
How do I replace the div on the page with all the jQuery objects in my array? I don't want to concatenate their HTML because I want to preserve the event handlers.
You can replace an element with an array of jQuery elements by doing this:
$(theElement).replaceWith(theArryaOfjQueryElements);
In your case, this is:
$('#replaceme').replaceWith(objs);
See the jQuery.replaceWith()
method.
BTW you have an error here:
j.click(function() { console.log('Clicked ' + i); });
This will always print Clicked 100
. The reason is that your function closes a reference to i
, not to it's value. So if i
is modified before this function is called, the function will see the new value of i
.
You should do this instead:
(function(i) {
j.click(function() { console.log('Clicked ' + i); });
}(i));
Use replaceWith
jQuery method which replaces each element in the set of matched elements with the provided new content.
var $obj = jQuery();//This will create an empty jQuery object
for(var i=0;i<100;i++) {
var j = jQuery('<div></div>');
j.click(function() { console.log('Clicked ' + i); });
$obj.add(j);//Using add method to add the jQuery object into $obj
}
$("#replaceme").replaceWith($obj);
var obs = [];
for(var i=0;i<100;i++) {
var j = jQuery('<div></div>');
j.click(function() { console.log('Clicked ' + i); });
obs.push(j);
}
$('#replaceme').html(objs);
/* or */
$('#replaceme').replaceWith(objs);
I read, that creating all elements at once is much faster then creating one by one. With the click function, you could count all previous siblings to get the index:
var str = ''
for (var i = 0; i < 100; i++) {
str += '<div></div>';
}
var elem = jQuery(str);
elem.click(function() { console.log('clicked '+jQuery(this).prevAll().length); });
jQuery('#replaceme').replaceWith(elem);
精彩评论