第一种方式用document.write
缺点: 创建好的元素会把之前页面中所有内容都替换了
document.getElementById('box').onclick=function () {
document.write("<h1>这是动态创建H1标签</h1>")
}
第二种方式:innerHTML="<p>内容</p>"
document.getElementById("button").onclick=function () {
document.getElementById("div").innerHTML="<p>这是动态创建p标签</p>";
document.getElementById("div").style.backgroundColor="pink"
}
第三种方式创建元素
1.var pObj=document.createElement("标签名")-----创建元素
2.父级元素.appendChild()
document.getElementById("button").onclick=function () {
//获取div
var dvObj=document.getElementById("div");
dvObj.style.backgroundColor="pink";
// 创建元素
var pObj=document.createElement("p");
dvObj.appendChild(pObj);
pObj.innerHTML="嘻嘻嘻";
pObj.style.fontSize="20px"
}
例如创建表格
<script language="javascript">
var o = document.body;
//创建表格
function createTable(w,h,r,c)
{
var table = document.createElement("table");
var tbody = document.createElement("tbody");
table.width = w;
table.height = h;
table.border = 1;
for(var i=1;i<=r;i++)
{
var tr = document.createElement("tr");
for(var j=1;j<=c;j++)
{
var td = document.createElement("td");
td.innerHTML = i + "" + j;
//td.appendChild(document.createTextNode(i + "" + j));
td.style.color = "#FF0000";
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(tbody);
o.appendChild(table);
}
createTable(270,270,9,9);
</script>