jquery – 切換 checkbox 的方法 prop() 與 attr()
jq 1.7.2之前可以用
$(selector).attr(“checked”,true);
$(selector).attr(“checked”,false);
來切換 checkbox 勾選
但今天換了1.9.1 之後的版本(我自己跳過1.8沒測),發現會沒反應
後來查了一下要使用 prop()
$(selector).prop(“checked”, true);
官方文件有說明這三個的比較 prop() attr() is()
這他們的範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
; html-script: false ]<!DOCTYPE html> <html> <head> <style> p { margin: 20px 0 0 } b { color: blue; } </style> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <input id="check1" type="checkbox" checked="checked"> <label for="check1">Check me</label> <p></p> <script> $("input").change(function() { var $input = $(this); $("p").html(".attr('checked'): <b>" + $input.attr('checked') + "</b><br>" + ".prop('checked'): <b>" + $input.prop('checked') + "</b><br>" + ".is(':checked'): <b>" + $input.is(':checked') ) + "</b>"; }).change(); </script> </body> </html> |