javascript的document中的动态添加标签实现方法

时间:2016-11-09103举报小编:youjiejie

    document添加标签,在document的语法中有一些节点的操作函数。具体包括:获取节点,改变节点,删除节点,替换节点,创建节点,添加节点,克隆节点等。我们可以利用这些函数动态改变html的节点。

    1、JavaScript

    <script type="text/javascript">
    function test1(){//对个节点的ID相同时候的情况
    var myhref = document.getElementById('same');
    window.alert(myhref.innerText);
    }
     
    function test2() {//输出节点的值
    var hobbies = document.getElementsByName("hobby");
    for (var i = 0; i < hobbies.length; i++) {
    if (hobbies[i].checked) {
    window.alert("你的爱好是:" + hobbies[i].value);
    }
    }
    }
     
    function getN() {//通过标签获取标签对应的值
    var myObj = document.getElementsByTagName('input');
    for (var i = 0; i < myObj.length; i++) {
    window.alert(myObj[i].value);
    }
    }
     
    function addtags() {//动态添加超链接节点<a></a>
    //(1)创建元素<a>
    var myElement = 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);
    }
     
    var i = 1;
    function addinput() {//添加input元素
    var myElement = document.createElement('input');
    myElement.type = "button";
    myElement.value = "奔跑吧";
    //myElement.id="i++";
    myElement.id = "id1";
    document.getElementById("div1").appendChild(myElement);
    }
     
    function deleteinput() {
    //删除一个元素的前提是要知道其父元素是什么。此方法不是很灵活
    //方法一
    //document.getElementById("div1").removeChild(document.getElementById('id1'));
    //方法二
    document.getElementById('id1').parentNode.removeChild(document
    .getElementById('id1'));
    }
    </script>

    2.body体中的调用

    <body>
    <a id="same" href="http://www.sohu.com">搜狐</a>
    <a id="same" href="http://www.baidu.com">百度</a>
    <a id="same" href="http://www.sina.com">新浪</a>
    <input type="button" value="提交" onclick="test1()"/>
    <!-- ID相同的时候只认识第一个 -->
     
    <hr/>
    <input type="checkbox" name="hobby" value="篮球"/>篮球
    <input type="checkbox" name="hobby" value="足球"/>足球
    <input type="checkbox" name="hobby" value="排球"/>排球
    <input type="button" value="提交" name="testing" onclick="test2()"/> 
     
    <!-- <hr/>
    <h1>获取指定标签的内容</h1>
    <input type="button" value="智能获取" onclick="getN()"> -->
     
    <hr/>
    <h1>智能添加标签</h1>
    <input type="button" value="智能添加" onclick="addtags()"/>
    <hr/>
    <h1>智能添加/删除input</h1>
    <div style="width:400px;height:300px;border:3px dashed red;" id="div1"></div>
    <input type="button" onclick="addinput()" value="inputAdd"/>
    <input type="button" onclick="deleteinput()" value="inputDelete"/>
     
    </body>

    以上。