Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

javascript - How to appendChild(element) many times. (The same element)

My question is: Is that possible to add the same element without rewriting the same variable. I am creating a slider, and i need to append a div with a class slide-el into block slider. Here is a part of code

    var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
    parts = 3,

    //Main html elements
    body = document.body,
    html = document.element,

    //viewport Height and Width
    vHeight = window.innerHeight,
    vWidth = window.innerWidth,

    sliderBody = _id("slider"),
    btnLeft = _id("btn-left"),
    btnRight = _id("btn-right"),

    urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
            "http://www.wallpapereast.com/static/images/pier_1080.jpg",
            "http://www.wallpapereast.com/static/images/pier_1080.jpg",
            "http://www.wallpapereast.com/static/images/pier_1080.jpg"];

    slide = _createEl("div");
    slide.className += "slide-el";

function _id(el){
  return document.getElementById(""+ el +"");
}
function _createEl(el){
  return document.createElement(""+ el +"");
}
window.onload = function(){
  slideLayout();
}

function slideLayout(){
  for(var i=0; i < urls.length; i++){
    sliderBody.appendChild(slide);
  }
}

The problem is that I can't append the same element that many times. It just creates one element instead of 4.

For you to understand better I made a fiddle:

https://jsfiddle.net/ud7dvn3z/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that:

for(var i=0; i < urls.length; i++){
  sliderBody.appendChild(slide.cloneNode());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...