添加HTML内容与文本内容以前用的是innerHTML与innerText方法,最近发现还有insertAdjacentHTML和insertAdjacentText方法,这两个方法更灵活,可以在指定的地方插入html内容和文本内容。
insertAdjacentHTML方法:在指定的地方插入html标签语句
原型:insertAdajcentHTML(swhere,stext)
参数:
swhere: 指定插入html标签语句的地方,有四种值可用:
1. beforeBegin: 插入到标签开始前
2. afterBegin:插入到标签开始标记之后
3. beforeEnd:插入到标签结束标记前
4. afterEnd:插入到标签结束标记后
stext:要插入的内容
示例:
<html>
<head>
<script language="javascript">
function myfun(){
var obj = document.getElementById("btn1");
obj.insertAdjacentHTML("afterEnd", "<br><input name=/"txt1/">");
}
</script>
</head>
<body>
<input name="txt"><input id="btn1" name="btn1" type="button" value="more" οnclick="myfun()">
</body>
</html>
************************************************************************************
<body οnlοad=addsome()>
<div id="paral" style="font-size:6;color='#ff00ff'">wwwwwwww</div><hr>
<script>
function addsome()
{
document.all.paral.insertAdjacentHTML("beforeBegin","<h4>aa</h1>");
document.all.paral.insertAdjacentHTML("afterBegin","<h1>bb</h1>");
document.all.paral.insertAdjacentHTML("beforeEnd","<h2>cc</h2>");
document.all.paral.insertAdjacentHTML("afterEnd","<h5>dd</h2>");
}
</script>
</body>
*************************************************************************************
<html>
<script>
var a = 0;
function Remove_button(obj){
obj.removeNode(true);
}
function Add_button(){
c_input.insertAdjacentHTML("beforeEnd", "<div id=bar" + a +
" style='background:red;width:40;height:20'" +
"οncοntextmenu='Remove_button(bar" +
a +
"); return false'>" +
a +
"sss</div>")
a++;
}
</script>
<input type="button" οnclick="Add_button()" value="add"><input type="button" οnclick="alert(c_input.innerHTML)" value="look">
<div id="c_input">
</div>
</HTML>