关于createElement、appendChild和insertBefore的用法

来源:互联网 发布:单片机usb转串口驱动 编辑:程序博客网 时间:2024/05/14 01:04

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testCreateElement.aspx.cs" Inherits="grid.testCreateElement" %>

<!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 runat="server">
    <title>无标题页</title>
<style type="text/css">
    div{
        border-style:solid;
        border-width:1px;
    }
</style>
</head>
<body>
    <form id="form1" runat="server">
   
   
    <div id="parentControl" >
        <a href="#">aaaaaaaaaaa</a>
    </div>
    </form>
   
<script type="text/javascript" language="javascript">
    
 
 //createElement()的用法
 
        var parentControl=document.getElementById("parentControl");
       
        //添加select
        var selectC = document.createElement("select");
            selectC.options[1] = new Option("加载1","1");
            selectC.options[2]=new Option("加载2","2");
            selectC.options[2].setAttribute("selected","selected"); //使其中一行显示
            selectC.size=1;                                         //显示的行数
            parentControl.appendChild(selectC);
           
        //添加Button
        var btnC=document.createElement("input");
            btnC.type="button";
            //或者
            //btnC.value="按钮"; 可见,setAttribute("value","按钮");可以在一控件中加入相应的属性或按钮的事件
            btnC.setAttribute("value","按钮");
            parentControl.appendChild(btnC);
           
//  下面来看  appendChild(btnC);与insertBefore()的用法;
           
        var btnA=document.createElement("input");     
            btnA.setAttribute("type","button");
            btnA.setAttribute("value","btnA");
           
            //parentControl.appendChild(btnA);
            //或者,这两个没什么区别
            //parentControl.insertBefore(btnA,null);
           
            parentControl.insertBefore(btnA,parentControl.childNodes[3]); //而这个语句,可以将btnAr按钮插入到parentControl中的任何位置
           
            //总结:insertBefore可以插入到子结点集的任何位置,但appendChild只能插入到子结点集的末尾。
           
        
 </script>
    <select>
        <option>ddd</option>
        <option >fff</option>
       
        <option selected="selected">kk</option>
    </select>
</body>
</html>

原创粉丝点击