相符情況下attr() prop()都可使用
不相符時僅prop()可用
Because "the attribute 'checked' corresponds only to the defaultCheckedproperty, and should only be used to set the initial value of the checkbox".
In fact, both attr() and prop() methods work, but as of jQuery 1.6, are used in different contexts:
— attr() is only used to check out if a checkbox was checked or not at first page load. In other words, it reflects what is written in your HTML source code, that is to say if the attribute 'checked' was initially present or not for a checkbox ( the name 'attr()' of this method can be used as a reminder) ;
— prop() on the other hand is used to check out in real time if a checkbox is currently checked or not — which is of course much more interesting — and to change this state, if needed. Here, we no longer deal with an attribute, but with a property (the name 'prop()' of this method can be used as a reminder).
The same principle applies for the boolean values returned by radio buttons or the <option> elements of a <select> input field for example.
https://cythilya.github.io/2017/09/10/jquery-attr-vs-prop/
沒有留言:
張貼留言