js - DOM -06 獲取元素屬性的幾種方式


1.

用.和[]的形式無法操作元素的自定義屬性; getAttribute可以操作元素的自定義屬性
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" id="text1" value="1111" _name = "miaowei"><br>
<img src="img/1.png" alt="無圖" id="img1" style="width: 100px; height: 100px">

<script>
    window.onload = function () {
        var oText = document.getElementById('text1');
        var oImg = document.getElementById('img1');
        oText.value = '2222';
        alert(oText.value); //2222

        oText['value'] = '3333';
        alert(oText['value']); //3333
        alert(oText.getAttribute('value')) //1111

        // 設置屬性值
        oText.setAttribute('value', '你好,世界');
        alert(oText.getAttribute('value')) // 你好,世界

        //移除屬性
        oText.removeAttribute('value');
        alert(oText.getAttribute('value')) // null

        //用.和[]的形式無法操作元素的自定義屬性 ; getAttribute可以操作元素的自定義屬性
        alert(oText._name); //undefined
        alert(oText['_name']); //undefined
        alert(oText.getAttribute('_name')); //miaowei
        console.log(oImg.src + ":" + oImg['src'] + oImg.getAttribute('src')); //http://localhost:63342/helloworld/img/1.png
    }
</script>

</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM