[英]Can't control appendChild() in Javascript
I have a trouble while split page by Javascript. 用JavaScript拆分页面时遇到麻烦。 I want to move 17 p tags into one div tag.
我想将17个p标签移动到一个div标签中。 So I have 34 p tags like this:
所以我有34个这样的p标签:
<p>1</p> <!-- Each p tag have the value is the number of the p tag -->
And then I have this Javascript code: 然后我有这个Javascript代码:
var p = document.getElementsByTagName("p");
var div = document.createElement("div");
for(i=0;i<17;i++){
div.appendChild(p[i]);
}
document.getElementsByTagName("body")[0].appendChild(div);
And the result I received is in the div tag, there are 17 p tags but the value of these p tag is odd number, which mean like this: 我收到的结果在div标签中,有17个p标签,但是这些p标签的值是奇数,这意味着:
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
This is the demo: http://jsbin.com/eyivic 这是演示: http : //jsbin.com/eyivic
Meantime, I want the p tags in the div tag will look like this: 同时,我希望div标签中的p标签看起来像这样:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
So what is the problem? 那是什么问题呢? How can I fix it?
我该如何解决? Thanks you so much!
非常感谢!
When you make an appendChild
on the div, it removes the element of your p
array. 在div上创建
appendChild
时,它将删除p
数组的元素。 This will make this "only odds" behaviour happens. 这将使这种“唯一的可能性”行为发生。 Let's say that you have 4 p elements.
假设您有4个p元素。
1, 2, 3, 4
If you make an appendChild
from p[0]
it will move your p element as you expected, but now your list is like this: 如果从
p[0]
appendChild
,它将按预期移动p元素,但是现在您的列表如下所示:
2, 3, 4
You are now pointing to p[1]
, that you were expecting that was the element 2, but it will be the element 3 instead. 现在,您指向
p[1]
,您期望它是元素2,但它将改为元素3。
To fix it you can always point to p[0]
and it will behave as you expect. 要修复它,您可以始终指向
p[0]
,它的行为将与您期望的一样。
Your loop should look like this: 您的循环应如下所示:
for(i=0;i<p.length;i++){
var newNode = p[i].cloneNode(true);
div.appendChild(newNode);
}
it is removed from your array when you do appendChild. 当您执行appendChild时,将从数组中删除它。 Cloning will solve your problem.
克隆将解决您的问题。
@memosdp pointed out that you actually want to remove those p elements from the original parent node. @memosdp指出,您实际上想从原始父节点中删除那些p元素。 In that case, when your loop is finished, just clear out the old parent node:
在这种情况下,循环完成后,只需清除旧的父节点即可:
// your loop is before this
var node = p[0].parentNode;
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.