我对clone()有个问题。
<div id="container">
<p id="template">a</p>
</div>
<script>
$(document).ready(function() {
$('#template').clone(true, true).appendTo('#container');
console.log($('#container').length); // it return 1, it supposed to return 2 right?, original and the cloned one.
});
</script>克隆后容器的长度是1,为什么不是2?
我查过:
console.log($('#container').eq(1));它返回未定义的。
克隆元素不应该成为索引1吗?
发布于 2016-01-12 08:19:16
$('#container')正在查看称为容器的div。因为您只看一个div,所以$('#container')的长度是1。
如果只想计算容器中段落元素的数量,可以使用以下命令:
console.log($('#container p').length);如果您想要计算元素的数量(不仅仅是段落),可以使用子()函数:
console.log($('#container').children().length);下面是一个JSFiddle,它显示了不同的选项,并有注释解释了三行代码:https://jsfiddle.net/0uzusuwz/
https://stackoverflow.com/questions/34738384
复制相似问题