我有一个关于JS检查复选框的问题.当我通过JS检查复选框时,它似乎在程序中被检查但在UI中它没有更新.
如果有人有解决方案
<!DOCTYPE html> <html> <head> <title>Check</title> <Meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" /> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script> <script> function getCheckedValue() { return ((document.getElementById("rock").checked)); } function setCheckedValue(toBeChecked){ document.getElementById(toBeChecked).checked="checked"; alert((document.getElementById(toBeChecked).checked)) alert($('#'+toBeChecked).attr('checked')) } </script> </head> <body> <div data-role="page"> <div data-role="header"> <h1>What kind/s of music do you listen to?</h1> </div><!-- /header --> <div data-role="content"> <input type="checkBox" class="music" name="music" id="rock" value="rock" > <label for="rock">Rock</label> <input type="button" value="Get" onclick="alert(getCheckedValue())"> <input type="button" value="Set" onclick="setCheckedValue('rock') "> </div> </div> </body> </html>
解决方法
我强烈建议您使用
prop而不是使用attr.
The preferred cross-browser-compatible way to determine if a checkBox is checked is to check for a “truthy” value on the element’s property using one of the following:
if ( elem.checked ) if ( $(elem).prop("checked") ) if ( $(elem).is(":checked") )
The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.
$("input").prop("disabled",false); $("input").prop("checked",true); $("input").val("someValue");