03JavaScript程序设计修炼之道 2019-06-23_14-32-17

11getAttribute&setAttribute.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <img  alt="this is a picture" aa="123">
    <script>
        var oImg = document.getElementsByTagName("img")[0];
        //alert(oImg.src);
        var srcValue = oImg.getAttribute("src");
        var altValue = oImg.getAttribute("alt");
        //alert(oImg.alt);
        //alert(oImg.aa); // undefined
        // 元素.属性 访问的元素固有的属性 不能访问自定义属性
        // 元素.getAtt..... 既可以获取元素固有的属性 也能访问自定义属性
        //alert(oImg.getAttribute("aa"));
        oImg.setAttribute("index",10); // 动态设置属性
        oImg.setAttribute("src","img/2.jpg");
        //alert(oImg.src);
     //oImg.bb = 100;//注意bb不算是元素的属性,所以
getAttribute不到值
     //alert(oImg.getAttribute("bb"));

oImg.removeAttribute("alt"); // 删除动态和标准的所有属性
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/HiJackykun/p/11107627.html