问题
I'm trying to repeatedly append an element defined outside the closure in a jQuery $.each()
loop see - http://jsfiddle.net/benedict_w/8Pczs/
Could someone please explain why the element is only appended in the last iteration of the loop?
e.g.
<ul>
<li>blah</li>
<li>blah</li>
<li>blah</li>
</ul>
using the following jquery:
var remove = $('<a href="#">remove</a>');
$('li').each(function(){
$(this).append(remove);
});
producers:
<ul>
<li>blah</li>
<li>blah</li>
<li>blah <a href="#">remove</a></li>
</ul>
回答1:
You're appending the same element each time.
Each append will move it to the next <li>
.
You need to clone()
the element (or just re-create it) for each iteration.
回答2:
$('<a href="#">remove</a>').appendTo('li');
This will append a new element to each li
while avoiding unnecessary loop and jQuery object creations.
If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.
http://api.jquery.com/appendTo/
回答3:
You don't need to clone the element to be inserted. According to the definition of append()
$('li').append('<a href="#">remove</a>');
//will append an <a> to every <li> in the "set of matched elements"
DEMO
UPDATE:
If you do need the each()
iterator to do other things, why not define your element inside of the closure?
$('li').each(function(){
var remove = $('<a href="#">remove</a>');
$(this).append(remove);
//do other things
});
UPDATE 2: Just keeping answer upto date from what I learned from OP's comments
Because in your question, you have reference to one unique element(defined outside the closure). Which, gets appended to the DOM on the first iteration. The next time you're trying to append that same element at another node in the DOM. jQuery recognizes that and so, detaches it from its place, creates another document fragment, then attaches it to its new target in the DOM.
回答4:
Define variable "remove" as plain text, that is
var remove = '<a href="#">remove</a>';
回答5:
var remo[enter link description here][1]ve = $(
is messing up your code. It is appending the element because of which it is happening.. Just pass it as a string instead of a selector or clone the object.. that should get the work done for you,,
var remove = '<a href="#">remove</a>' ;
$('li').each(function(){
$(this).append(remove);
});
Also you can use appendTo to avoid the iteration
$('<a href="#">remove</a>').appendTo('li');
check the UPDATED FIDDLE
来源:https://stackoverflow.com/questions/12411106/jquery-append-element-during-each