0

我正在尝试将复选框检查事件与其他事件(例如对话框显示)挂钩。但是,当我在浏览器中测试我的 html 文件时,我似乎无法让 click 事件工作。不过,它确实在 JSFiddle 中工作,这很奇怪。

http://jsfiddle.net/rEgAX/1/

我的 HTML:

<label><input type="checkbox" name="checkbox-0" id="myCheckbox" /> Completed </label>

我的 JavaScript:

var countChecked = function() {
    if ($("#myCheckbox").is(":checked"))
    {
        alert('checked!');
    }
};

$( "input[type=checkbox]" ).on( "click", countChecked );

我写的html文件:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
        <script>
            // On clicking of the completed checkbox, we want to pop up a dialog for confirmation.
            var checkboxClicked = function() {
                if ($("#myCheckbox").is(":checked")) {
                    alert('checked!');
                        console.log('checked!')
                    }
                };

            $( "input[type=checkbox]" ).on( "click", checkboxClicked );

        </script>
    </head>
    <body>
        <label><input type="checkbox" name="checkbox-0" id="myCheckbox" /> Completed </label>
    </body>
</html>
4

2 回答 2

3

您必须将代码放入

$(document).ready(function(){
    ...
});

由于您的脚本在您的复选框被渲染之前出现。

编辑

您可能会遇到我的第一个答案的问题。感谢 Omar 的评论和参考

它应该是这种方式而不是.ready()功能:

$(document).on('pageinit') { 
    ...
});
于 2013-08-15T02:08:17.613 回答
0

默认情况下,jsFiddle 会将您的代码包装在负载处理程序中。

尝试将您的代码包装在:

$(window).load(function(){
var countChecked = function() {
    if ($("#myCheckbox").is(":checked"))
    {
        alert('checked!');
    }
};

$( "input[type=checkbox]" ).on( "click", countChecked );
});  
于 2013-08-15T02:07:12.863 回答