jquery: agrupa o concatena objetos jquery creados por un bucle, para usar appendTo solo una vez

Tengo un for loop to generate a row of divs, my code is

for(j=0; j<7; j++) {
   $('<div/>', {
     id: 'unique',
     html: 'whatever'
}).appendTo('#container');

This code seems to seek out #container for every iteration and appends a new div to it.

How do write the code so that I can go create all the divs first and then append to the container all at once? Sorry, I tried searching for keywords such as concatenate/group/add jquery objects, and don't seem to have the right search results.

TIA

preguntado el 10 de marzo de 12 a las 02:03

Why do you want to have the code only call appendTo ¿una vez? -

@JaredPar, because as I understand it, jquery only has to seek out the correct div once instead of many times as the iteration of the loop. -

2 Respuestas

Xander's solution should work just fine. I personally don't like working with 'long' HTML strings in js. Here is a solution that looks more similar to your code.

var elements = [];
for(j=0; j<7; j++) {
    var currentElement = $('<div>', { id: i, text: 'div' });
    elements.push(currentElement[0]);
}
$('#container').append(elements);

respondido 10 mar '12, 03:03

Thanks Justin, this is kinda what I had in mind. I do wonder if there is another way of 'grouping' objects, since this method introduces an array that could tax resources. - jamex

Yes, you could potentially pay a slight tax on the creation of jQuery objects. However, you get added benefits of more easily binding events (you'd probably want to delegate the events if they're the same for every element), plus this way gives you the added benefit of creating a closure on those events(not demonstrated here), if needed. I don't think you will see any performance gains until you reach thousands of elements. - justin

Hi Justin, the code works, but I don't understand the line elements.push(currentElement[0]); Why does currentElement has the [0]? - jamex

It is because a jQuery object is created and you don't want to add the whole object just the first element in it. A jQuery object is similar to an array. - justin

Thanks Justin, can you point me to where I can learn more about what elements are part of the object? - jamex

Esto podria ayudar

var htm = '';
for(j=0; j<7; j++) {
     htm+= '<div id="unique_'+i+'">whatever</div>';
}

$('#container').html(htm); // Or append instead of html 

respondido 10 mar '12, 03:03

Thanks Jose/Xander, I did not really want to do it that way because I didn't want to mess with writing the text string. I think Justin's code is more of what I had in mind. - jamex

OTOH, the creation of the string variable should be less taxing than jquery objects. - jamex

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.