HTML页面:
第一元素
FIRST ELEMENT的onclick功能(< h1>)具有以下功能:
function insert(event)
{
elem = document.getElementById("first");
element = document.createElement("div");
element2 = document.createElement("a");
element2.href = "www.google.com";
element2.innerHTML = "GOOGLE" + n;
element.appendChild(element2);
//element.innerHTML = "text content";
element.style.position = "relative";
element.style.backgroundColor = "yellow";
element.style.left = "10px";
element.style.top = "30px";
elem.appendChild(element);
//document.body.appendChild(element);
event.target.appendChild(element);
n++;
}
单击“FIRST ELEMENT”两次输出为:
FIRST ELEMENT
GOOGLE1
GOOGLE2
但我希望输出为:
FIRST ELEMENT
GOOGLE2
GOOGLE1
我怎样才能做到这一点?
答案 0 :(得分:1)
您可以使用insertBefore重新排列元素子元素的顺序。 这是你想要的:
var n = 1;
function myfunc(event)
{
elem = document.getElementById("first");
element = document.createElement("div");
element2 = document.createElement("a");
element2.href = "www.google.com";
element2.innerHTML = "GOOGLE" + n;
element.appendChild(element2);
element.style.position = "relative";
element.style.backgroundColor = "yellow";
element.style.left = "10px";
element.style.top = "30px";
elem.appendChild(element);
children = elem.children;
if(typeof(children) != "undefined" && children.length > 1){
num = children.length - 1;
elem.insertBefore(children[num], children[1]);
}
n++;
}
指向工作样本的链接:http://jsfiddle.net/szNcT/