用javascript定義和操作自訂HTML元素

來源:互聯網
上載者:User

前面的文章探討了使用javascript來操縱HTML元素的自訂屬性,那麼在HTML頁面中,除了系統支援的HTML元素外,是否可以建立自訂的HTML元素呢?答案是可以的。

自訂的HTML元素與系統自身的HTML元素地位相同,都可以用document.getElementById來獲得,區別在於,自訂的HTML元素都是不可見的,類似於隱藏控制項。

使用自訂HTML元素,我們就可以建立多種隱藏控制項,而不一定拘泥於只能建立input的hidden元素了;另外,還可以用於某些特定方面的需求!

如在HTML頁面中直接建立:

象建立系統內建的HTML元素那樣添加:

var cy = document.createElement("YYY");
cy.id = "customControl_YYY";
cy.value = "自訂元素yyy";
cy.checked = true;
document.body.appendChild(cy);

2)用javascript來操作:

alert(document.getElementById("customControl_YYY").value);
alert(document.getElementById("customControl_YYY").checked);

在這裡,Firefox支援直接取值,而不須用attributes屬性集合。

代碼如下:

<html>
    <head>
        <title>用javascript定義和操作自訂HTML元素</title>
        <script language="javascript">
            function getXXXValue()
            {
                //alert(document.getElementById("customControl_XXX").value);                                                //IE中可以使用
                alert(document.getElementById("customControl_XXX").attributes["value"].value);            //IE Firefox中均可使用
            }
            
            //IE Firefox中均可使用
            function createYYYControl()
            {
                var cy = document.createElement("YYY");
                cy.id = "customControl_YYY";
                cy.value = "自訂元素yyy";
                cy.checked = true;
                document.body.appendChild(cy);
                
                alert(document.getElementById("customControl_YYY").value);
                alert(document.getElementById("customControl_YYY").checked);
            }
        </script>
    </head>
    <body>
        <xxx id="customControl_XXX" value="自訂元素xxx"></xxx>
        <input type="button" value="取得xxx元素的值" onclick="getXXXValue();">
        <input type="button" value="產生yyy元素並取得該元素的值" onclick="createYYYControl();">
    </body>
</html>


原始碼:http://files.cnblogs.com/redleaf1995/CustomHtmlControl.rar

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.