1

我的代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="jquery.js"></script>
<script>
$(function(){
    $("body").on("click",".mes_sel",function(){
        if($(".mes_sel:checked").length==0){
            alert("Checked");
        }
        else alert("Not Checked");
    });
});
</script></head>
<body>
<input type="checkbox" class="mes_sel">
</body>
</html>

未选中文本框时会发出警报,因为 onclick 在检查复选框之前正在运行。如何在检查/取消选中输入后运行单击事件

4

3 回答 3

1

用于change

$(function(){
    $(".mes_sel").on("change", function(){
        if($(this).is(':checked')){
            alert("Checked");
        } else {
            alert("Not Checked");
        }
    });
});​

演示

于 2012-06-22T15:07:50.797 回答
0

试试这个:

$("body").on("click", ".mes_sel", function() {
    if ($(this).is(":checked")) {
        alert("Checked");
    }
    else alert("Not Checked");
});​

jsFiddle 示例

于 2012-06-22T15:12:30.397 回答
0

不久前我遇到了这个问题——我还发现不同的浏览器处理这个问题的方式不同。如果我没记错的话,Chrome 是最严重的违规者。

这不一定是最好的解决方案,但您可以将自定义属性附加到每个复选框,例如“isChecked”,然后将您的函数基于此属性,如下所示:

if ($("mes_sel").attr("isChecked") == "true") { ... }

Like I said, not the best solution as you will have to manually flip the "isChecked" attribute in order to stay consistent with the actual checked value of the checkbox, but it will work if nothing more elegant will work for you.

If you'd like an example of this , check out this jsFiddle:

http://jsfiddle.net/NathanFriend/GAP2j/

This turns regular radio buttons into "toggleable" radio buttons - I was forced to use this custom attribute method because of the different way browsers execute onclick events.

于 2012-06-22T15:13:35.643 回答