DOM--document的一些方法

body\document都是window中的一个对象,我们常用的操作都在document 中进行,document表示当前的页面文档。它有以下几个经典常用的方法:

getElementById():根据标签ID获取要操作的标签。

getElementByName():根据标签名称获取要操作的一组标签数组,如有相同名称的radio等标签

getElementByTagName():根据标签的类型获取要操作的一组标签数组,如input类型等

 

另动态增加标签用到的有如下函数:

createElement("标签类型"),然后用appendChild()加进去即可,用removeChild()是去除此标签控件。

另:标签的innerText只是显示标签的内容,而innerHtml显示的是带有格式的html源码的内容。

如下功能:

分别显示性别的id,以及动态增加一个select 和button,且button关联一个事件,显示label的value:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function ShowCheckBoxValue() {
            var chks = document.getElementsByName("gender");
            if (chks) {
              var svalue="";
              for(var i=0;i<chks.length;i++) {
                 svalue+=chks[i].id;                 
              }
              document.getElementById("ara1").value = svalue;
            }

      }
      function clickme() {  //新增的事件
        alert(document.getElementById('mylabel').innerText);
      }
      function dynamicAddSelect() {
          var selobj = document.createElement("select");
          selobj.innerHTML = "<option>aa</option><option>bb</option><option>cc</option>";  //非常好用的属性
          document.body.appendChild(selobj);

          var btn = document.createElement("input");
          btn.type = "button";
          btn.value = "我是新增的";
          btn.onclick = clickme;
          document.body.appendChild(btn);
          
      }
    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="checkbox" id="Male" name="gender"/><label id="mylabel" for="Male">男</label>
        <br />
    <input type="checkbox" id="Female" name="gender"/><label for="Female">女</label>
        <br />
    <input type="checkbox" id="unKnown" name="gender"/><label for="unKnown">保密</label>
    <br />
    <input type="button" value="得到三个checkbox的名称" onclick ="ShowCheckBoxValue()"/>&nbsp;
    <textarea id="ara1" rows=5></textarea>
    <input type="button" value="动态增加select" onclick="dynamicAddSelect()">
   
    </div>

    </form>
</body>
</html>

 

posted on 2013-05-20 15:47  天上星  阅读(334)  评论(0编辑  收藏  举报

导航