为什么这个只有一次附加?

时间:2022-01-03 06:50:34

This loop (see jsfiddle) tries to append a <span> tag to a container five times. But it only does it once. Why?

这个循环(参见jsfiddle)尝试将标记附加到容器中五次。但它只做一次。为什么?

var myArr = [0,1,2,3,4];
var $span= $('<span></span>');
for (var i = 0; i < (myArr.length); i++) {
    $('.contain').append($span);
}

1 个解决方案

#1


7  

The problem is that you're appending the same element multiple times.
Use clone to clone the element and then append.

问题是,您将同一元素附加多次。使用克隆来克隆元素,然后添加。

$('.contain').append($span.clone());

$(' .contain ').append($ span.clone());

demo

演示

Update:

更新:

This way you can customize your element and then clone it with all properties.

这样您就可以自定义元素,然后用所有属性克隆它。

var $span = $('<span/>', {
                    'class': 'someClass otherClass',
                    'css': {
                         'background-color': '#FF0000'
                     }
            });
for (var i = 0; i < (myArr.length); i++) {
    $('.contain').append($span.clone());
}

demo2

以及接下来

Update2: according to this comment.

Update2:根据这个评论。

$('.contain').append('<span class="yourClass"/>');

$(' .contain ')。追加(“< span class = " yourClass " / > ');

#1


7  

The problem is that you're appending the same element multiple times.
Use clone to clone the element and then append.

问题是,您将同一元素附加多次。使用克隆来克隆元素,然后添加。

$('.contain').append($span.clone());

$(' .contain ').append($ span.clone());

demo

演示

Update:

更新:

This way you can customize your element and then clone it with all properties.

这样您就可以自定义元素,然后用所有属性克隆它。

var $span = $('<span/>', {
                    'class': 'someClass otherClass',
                    'css': {
                         'background-color': '#FF0000'
                     }
            });
for (var i = 0; i < (myArr.length); i++) {
    $('.contain').append($span.clone());
}

demo2

以及接下来

Update2: according to this comment.

Update2:根据这个评论。

$('.contain').append('<span class="yourClass"/>');

$(' .contain ')。追加(“< span class = " yourClass " / > ');