This morning, the beautiful test sister raised a strange bug, said I a function checkbox in and out, such as the first time to open a tick, the nth opening may not be selected.
Think of a close contact with the beauty of the opportunity, immediately chicken move up.
After a couple of layers of stripping cocoon (da da Jiang You), finally know the reason: attr () in two times check box, invalid.
For example, the following HTML page, a little "check", two points "uncheck", Three points "check", see, not a chant.
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "Utf-8"> <title>Prop Demo</title> <style>img{padding:10px; }Div{Color:Red;font-size:24px; } </style> <Scriptsrc= "Https://code.jquery.com/jquery-1.10.2.js"></Script></Head><Body> <inputtype= "checkbox"checked= "Checked"> <inputtype= "checkbox"> <inputtype= "checkbox"> <inputtype= "checkbox"checked= "Checked"> <Script>$( "input[type= ' checkbox ']"). Prop ("checked", function(I, Val) {return !Val;});</Script> </Body></HTML>
1.html
The solution is to use prop () to replace the attr () method (above the Jquery1.6), as in the following code:
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "UTF-8"><title>Attr checked</title><Scripttype= "Text/javascript"src= "./js/jquery-1.11.2.js"></Script><Scripttype= "Text/javascript"> functionswitchchecked (flag) {$ ("input[type= ' checkbox ']"). Prop ('checked', flag); }</Script></Head><Body> <inputtype= "checkbox" /> <inputtype= "button"onclick= "switchchecked (true)"value= "Checked"> <inputtype= "button"onclick= "switchchecked (false)"value= "Uncheck"></Body></HTML>
2.html
For official documents, see: http://api.jquery.com/attr/
or http://api.jquery.com/prop/.
Excerpt as follows: "As of the JQuery 1.6, the. attr () method returns undefined for attributes", which has not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the. Prop () m Ethod. "
Jquery,checkbox cannot be checked with attr () two times