js基础-操作节点属性

111 阅读1分钟
<body>
    <img src="" width="400" height="300" >
    <!-- 
        操作节点属性
设置属性
获取属性
删除属性
setAttribute()方法添加指定的属性,并为其赋指定的值
getAttribute() 方法返回指定属性名的属性值
removeAttribute() 方法删除指定的属性
     -->
     
         let img = document.getElementsByTagName('img')[0];
         let imgSrc = 'https://ns-strategy.cdn.bcebos.com/ns-strategy/upload/fc_big_pic/part-00050-3493.jpg'
         /* img.src =  */
         img.setAttribute('src',imgSrc);
         /* img.setAttribute('height','600'); */
         /* 自定义属性 */
         img.setAttribute('data-str','不要怕修空调找张老师');
         /* let src = img.getAttribute('src');
         console.log(src); */
         /* 获取不到值返回null */
         /* if(!img.getAttribute('data-src')){
             document.write('后台返回的值没找到');
         }else{
            let str = img.getAttribute('data-str');
            document.write(str);
         } */

         img.onclick = function(){
            img.removeAttribute('data-str')
         }