javascript的document中的动态添加标签实现方法
document的高级篇中提供了节点操作的函数,具体包括:获取节点,改变节点,删除节点,替换节点,创建节点,添加节点,克隆节点等函数。我们可以利用这些函数动态改变html的节点。
1、JavaScript
<scripttype="text/javascript">
functiontest1(){//对个节点的ID相同时候的情况
varmyhref=document.getElementById('same');
window.alert(myhref.innerText);
}
functiontest2(){//输出节点的值
varhobbies=document.getElementsByName("hobby");
for(vari=0;i<hobbies.length;i++){
if(hobbies[i].checked){
window.alert("你的爱好是:"+hobbies[i].value);
}
}
}
functiongetN(){//通过标签获取标签对应的值
varmyObj=document.getElementsByTagName('input');
for(vari=0;i<myObj.length;i++){
window.alert(myObj[i].value);
}
}
functionaddtags(){//动态添加超链接节点<a></a>
//(1)创建元素<a>
varmyElement=document.createElement("a")
//(2)给元素添加必要的标示信息
myElement.href="http://www.sina.com";
myElement.innerText="连接到新浪";
myElement.style.left="200px";
myElement.style.top="300px";
myElement.style.position="absolute";
//添加到document.body
document.body.appendChild(myElement);
}
vari=1;
functionaddinput(){//添加input元素
varmyElement=document.createElement('input');
myElement.type="button";
myElement.value="奔跑吧";
//myElement.id="i++";
myElement.id="id1";
document.getElementById("div1").appendChild(myElement);
}
functiondeleteinput(){
//删除一个元素的前提是要知道其父元素是什么。此方法不是很灵活
//方法一
//document.getElementById("div1").removeChild(document.getElementById('id1'));
//方法二
document.getElementById('id1').parentNode.removeChild(document
.getElementById('id1'));
}
</script>
2.body体中的调用
<body> <aid="same"href="http://www.sohu.com">搜狐</a> <aid="same"href="http://www.baidu.com">百度</a> <aid="same"href="http://www.sina.com">新浪</a> <inputtype="button"value="提交"onclick="test1()"/> <!--ID相同的时候只认识第一个--> <hr/> <inputtype="checkbox"name="hobby"value="篮球"/>篮球 <inputtype="checkbox"name="hobby"value="足球"/>足球 <inputtype="checkbox"name="hobby"value="排球"/>排球 <inputtype="button"value="提交"name="testing"onclick="test2()"/> <!--<hr/> <h1>获取指定标签的内容</h1> <inputtype="button"value="智能获取"onclick="getN()">--> <hr/> <h1>智能添加标签</h1> <inputtype="button"value="智能添加"onclick="addtags()"/> <hr/> <h1>智能添加/删除input</h1> <divstyle="width:400px;height:300px;border:3pxdashedred;"id="div1"></div> <inputtype="button"onclick="addinput()"value="inputAdd"/> <inputtype="button"onclick="deleteinput()"value="inputDelete"/> </body>
以上就是小编为大家带来的javascript的document中的动态添加标签实现方法全部内容了,希望大家多多支持毛票票~