I have a piece of code like this -
<script>
var x,m,cloneNodex;
function addVtier() {
m.appendChild(cloneNodex);
}
function load() {
x = document.getElementById("vtier#1");
cloneNodex = x.cloneNode(true);
m = document.getElementById("main");
}
</script>
<body onload = load();>
<div id = "main">
<table id = "vtier#1" width="100%" class="heading">
<tr>
<td>
<button onclick=addVtier();>clone</button>
</td>
<td> 1.Vtier Name:
<select>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
</td>
</tr>
</table>
</div>
</body>
Now my question is that why this appends the cloned node i.e. the table with id="vtier#1" only once and not as many times as the CLONE button is pressed ?
I have a piece of code like this -
<script>
var x,m,cloneNodex;
function addVtier() {
m.appendChild(cloneNodex);
}
function load() {
x = document.getElementById("vtier#1");
cloneNodex = x.cloneNode(true);
m = document.getElementById("main");
}
</script>
<body onload = load();>
<div id = "main">
<table id = "vtier#1" width="100%" class="heading">
<tr>
<td>
<button onclick=addVtier();>clone</button>
</td>
<td> 1.Vtier Name:
<select>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
</td>
</tr>
</table>
</div>
</body>
Now my question is that why this appends the cloned node i.e. the table with id="vtier#1" only once and not as many times as the CLONE button is pressed ?
Share Improve this question edited Jan 18, 2012 at 20:11 linusunis fed asked Jan 18, 2012 at 19:33 linusunis fedlinusunis fed 1932 gold badges6 silver badges15 bronze badges 1-
1
Should
m.appendChild(nodex);
bem.appendChild(cloneNodex);
? – Mike Samuel Commented Jan 18, 2012 at 19:36
2 Answers
Reset to default 4Because there is only one clone.
var y = node;
x.appendChild(y);
x.appendChild(y);
Only appends y once because there is only one y.
<body>
<div id = "main">
<table id = "vtier#1" width="100%" class="heading">
<tr>
<td>
<button>clone</button>
</td>
<td> 1.Vtier Name:
<select>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
</td>
</tr>
</table>
</div>
<script>
(function () {
var main = document.getElementById("main"),
vtier = document.getElementById("vtier#1").cloneNode(true);
document.getElementsByTagName("button")[0].addEventListener("click", addClone);
function addClone() {
main.appendChild(vtier.cloneNode(true));
}
}());
</script>
</body>
Also fixed up the code for you by removing globals and using unobtrusive event listeners.
Appending a node that is part of the DOM first removes it from its current location so you will not get two clones by adding the same node twice.
This seems to be what you're doing some you only call cloneNode
once, not every time the clone button is clicked.
Move the cloneNodex =
out of load
into addVtier
and you should get multiple copies.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744721836a4589954.html
评论列表(0条)