鍍金池/ 問答/Python  HTML/ 通過JS給input標(biāo)簽添加的checked屬性后,再調(diào)用removeAttri

通過JS給input標(biāo)簽添加的checked屬性后,再調(diào)用removeAttribute()方法,為什么刪除不了?

removeAttribute()我知道可以刪除標(biāo)簽上的屬性,但是通過JavaScript給input標(biāo)簽添加checked的屬性后,再調(diào)用removeAttribute()方法,為什么刪除不了?有沒有大佬幫忙解釋一下?

<input type="checkbox" id="input">removeAttribute()
    <script>
        var input = document.getElementById('input');
        input.checked=true;
        input.removeAttribute('checked');
        //結(jié)果這個(gè)checked固有屬性似乎沒有被刪除(因?yàn)榍岸隧撁嬷幸廊槐贿x中),但是dom樹上也沒有這個(gè)checked屬性
        input.class="demo";
        input.removeAttribute('class');
        //這個(gè)class固有屬性成功刪除了
    </script>

clipboard.png

回答
編輯回答
懷中人

先說答案:.prop( "checked", false )

有興趣可以看看為什么?

https://jquery.com/upgrade-gu...

Prior to jQuery 3.0, using .removeAttr() on a boolean attribute such as checked, selected, or readonly would also set the corresponding named property to false. This behavior was required for ancient versions of Internet Explorer but is not correct for modern browsers because the attribute represents the initial value and the property represents the current (dynamic) value.

It is almost always a mistake to use .removeAttr( "checked" ) on a DOM element. The only time it might be useful is if the DOM is later going to be serialized back to an HTML string. In all other cases, .prop( "checked", false ) should be used instead.

2017年10月9日 21:39