samedi 25 avril 2015

Use jQuery add() to add element in a loop


How do I use jQuery's add() to add an element in a loop?

http://ift.tt/1HCJ4Y1

var allFields1 = $([]).add($('<input/>')).add($('<input/>').add($('<input/>')));
console.log(allFields1);

var allFields2 = $([]);

$([1,2,3]).each(function (index) {
    var input=$('<input/>').val(index);
    allFields2.add(input);
})

console.log(allFields2);

I see why my above code doesn't work as described by http://ift.tt/ORNyRx, but don't know how to do it.

The following will not save the added elements, because the .add() method creates a new set and leaves the original set in pdiv unchanged:

var pdiv = $( "p" );
pdiv.add( "div" ); // WRONG, pdiv will not change


Aucun commentaire:

Enregistrer un commentaire