比较好玩的动态添加网页元素
javascript 有一些很有趣的功能。下面介绍三样小功能。
1.动态创建按键
2动态创建链接
3动态创建表格
效果如下:
源代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function btnClick() {
var divMain = document.getElementById('divMain');
var input = document.createElement("input");
input.type = "button";
input.value = "我是动态按钮";
divMain.appendChild(input);
}
function linkCreate() {
var divlink = document.getElementById("divlink");
var link = document.createElement("a");
link.href = "http://www.baidu.com";
link.innerText = "百度";
divlink.appendChild(link);
}
function tableCreate() { var data = { "google":"http://www.google.com","搜狐":"http://www.souhu.com","百度":"http://www.baidu.com" }
var tablediv = document.getElementById("tablediv");
for (var key in data) {
var value = data[key];
var tr = document.createElement("tr");
var td1 = document.createElement("td");
td1.innerText = key;
tr.appendChild(td1);
var td2 = document.createElement("td");
td2.innerHTML = "<a href='" + value + "'>"+value+"</a>";
tr.appendChild(td2);
tablediv.appendChild(tr);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="divMain">
</div>
<div id="divlink">
</div>
<div id="tablediv">
</div>
<input id="Button1" type="button" value="动态创建按钮" id="Button2"
type="button" value="动态创建链接" /><input id="Button3" type="button"
value="创建一个链接的表格" />
</form>
</body>
</html>
本文转自gauyanm 51CTO博客,原文链接:http://blog.51cto.com/gauyanm/422284,如需转载请自行联系原作者