<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CreateElement的两种创建方式_www.jb200.com</title>
<script type="text/javascript">
function CreateButton1() {
var btn = document.createElement("input");
btn.type = "button";
btn.value = "我是动态创建的1";
btn.onclick = function () {
alert(this.value);
}
document.body.appendChild(btn);
}
function CreateButton2() {
var btn = document.createElement("<input type='button' value='我是动态创建的2' " +
"onclick='OnClick2(this)' />");
document.body.appendChild(btn);
}
function OnClick2(btn) {
alert(btn.value);
}
function CreateLink() {
var link = document.createElement("<a href='http://www.baidu.com'>
百度</a>");
//注意这里链接的文本“百度”是不会显示出来的,必须设置innerText或innerHTML
link.innerText = "百毒";
document.body.appendChild(link);
}
function CreateLabel() {
var lbl = document.createElement("label");
lbl.setAttribute("for", "userName");
lbl.setAttribute("myAge", "12"); //可以设置自定义标示
lbl.innerText = "用户名:";
document.body.appendChild(lbl);
}
</script>
</head>
<body>
<input type="button" value="动态创建按钮1" onclick="CreateButton1()" />
<input type="button" value="动态创建按钮2" onclick="CreateButton2()" />
<input type="button" value="动态创建链接" onclick="CreateLink()" />
<input type="button" value="动态创建Label" onclick="CreateLabel()" />
<input type="text" id="userName" value="李莫" />
</body>
</html>