關於createElement、appendChild和insertBefore的用法

來源:互聯網
上載者:User

<%@ 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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.