JavaScript可以在JSFiddle中使用,但不能在浏览器的html文件中使用

时间:2013-08-15 02:02:23

标签: javascript jquery jquery-mobile checkbox onclick

我正在尝试使用其他事件(例如对话框显示)来挂钩复选框检查事件。但是,当我在浏览器中测试我的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>

2 个答案:

答案 0 :(得分:3)

您必须将代码放在

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

由于您的脚本在呈现复选框之前出现。

修改

你的第一个答案可能会遇到问题。感谢Omar的评论和reference

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

$(document).on('pageinit') { 
    ...
});

答案 1 :(得分:0)

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

尝试将代码包装在:

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

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