开发者

Why do multiple `.appendTo` calls on a newly created jQuery element only append it once?

开发者 https://www.devze.com 2023-02-21 12:42 出处:网络
I’m trying to add five new list items to the end of the unordered list #myList. My approach was to do the following:

I’m trying to add five new list items to the end of the unordered list #myList. My approach was to do the following:

const $newItem = $("<li>New Item</li>");
const $ul = $("#myList");

for(let i = 0; i < 5; ++i){
  $newItem.appendTo($ul);
}

However this doesn’t work as it only inserts one list item into the list, not five.

In R. Murphy’s jQuery Fundamentals (in the Manipulation exercises in the jQuery Basics secti开发者_Python百科on), the solution provided by the author is very close to mine, the only difference being she doesn’t store the new list item in a variable, but rather uses an HTML string:

const $ul = $("#myList");

for(let i = 0; i < 5; ++i){
  $("<li>List item " + i + "</li>").appendTo($ul);
}

It seems like my approach should work also, so I’m struggling to understand why it doesn’t. Why is this?


Your approach creates a single li element outside of the loop and tries to append the same thing to the ul five times. But since you hold a reference to a single li, each time you append it, it actually removes it from where it is and re-adds it there..

In the solution the li is created inside the loop so it is a new li element each iteration.

You could change your own to use the .clone() docs method

for (var i=0;i<5;i++){
    $newItem.clone().appendTo($ul);
};

This way it will create a copy and you then add that to the ul.


you can also repalce the pointer

$newItem

into the loop

example:

var $ul = $('#myList');
for (var i=0;i<5;i++)
{
var $newItem = $('<li>New Item</li>');
$newItem.appendTo($ul);
};
0

精彩评论

暂无评论...
验证码 换一张
取 消