我有一个简单的表格:
HTML:
<form>
<input id="radio1" type="radio" name="radio-button" value="male" class="file">Choose a picture from file<br>
<input id="radio2" type="radio" name="radio-button" value="female" class="choose">Use example picture<br>
</form>
JS:
$(document).ready(function() {
if($('#radio1').is(':checked')) {
alert("it's checked");
}
});
当我检查#radio1没有任何事情发生,没有警报,控制台没有错误,发生了什么?
答案 0 :(得分:4)
您正在测试当DOM准备就绪时选中单选按钮而当检查状态更改时
$(document).ready(function() {
$('#radio1').on('change', function () {
if($(this).is(':checked')) {
alert("it's checked");
};
});
});
答案 1 :(得分:3)
当文档准备就绪时,您的JS只执行一次:然后取消选中该复选框。您需要处理复选框上的点击。
答案 2 :(得分:2)
在这种情况下,您只检查在加载文档时是否检查过它。 您应该将事件处理程序附加到复选框以查看该状态何时更改。 检查一下:https://stackoverflow.com/a/7236837/146513