JS JQ操作属性

JS 操作属性

1. 设置,获取,移除

setAttribute()  getAttribute()  removeAttribute()

<body>
    <input type="text" class="input" value="test" data-value="1111">
    <button class="btn" >btn1</button>
    <button class="btn">btn2</button>
    <button class="btn">btn3</button>
</body>
<script>
    var dom = document.getElementsByClassName('input')[0];
    var btns = document.getElementsByClassName('btn');
    
    // hasAttribute()    判断对象是否有某属性,返回一个 Boolean 值。
    console.log(dom.hasAttribute('data-value'));    // true
    console.log(dom.hasAttribute('placeholder'));    // false
    
    btns[0].onclick = function() {
        // 获取属性值
        var text = dom.getAttribute('value');
        var className = dom.getAttribute('class');
        var id = dom.getAttribute('id');    // 获取没有的属性返回null
        // 设置/修改属性
        dom.setAttribute('value', className+text+id);
        dom.setAttribute('disabled', 'disabled');
        this.setAttribute('disabled', 'disabled');
    }
    btns[1].onclick = function() {
        // 移除属性
        dom.removeAttribute('disabled');
        btns[0].removeAttribute('disabled');
    }
</script>

猜你喜欢

转载自www.cnblogs.com/xinghong/p/11242020.html