jQuery .each() not equivelant to calling a method directly on the selector?
I've never had this issue before, so I'm somewhat lost. I'm getting two different results using essentially the same underlying code. The first way is this:
$(".myClassSelector").append(somejQueryObject);
The second way, which doesn't appear to work the same, is this:
$(".myClassSelector").each(function() { $(this).appen开发者_如何学God(somejQueryObject) });
The second example only appends somejQueryObject to the last .myClassSelector found.
My guess is that with the first approach jQuery internally clones the jQuery object for each of the matched elements of the selector, while with the second it just keeps appending the same object (thus removing it from earlier appended elements). Try this:
$(".myClassSelector").each(function() { $(this).append(somejQueryObject.clone()) });
When you use append on a jQuery object, it moves the object form its current location to the new location. Each iteration of your loop moves somejQueryObject
to the next element. clone()
is needed if you want to append a copy to each element.
精彩评论