【问题标题】:JavaScript works in JSFiddle but not in html file on a browserJavaScript 在 JSFiddle 中有效,但在浏览器的 html 文件中无效
【发布时间】:2013-08-15 18:32:35
【问题描述】:

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

【问题讨论】:

  • 更多细节。什么浏览器?控制台是否显示错误?我们并不神奇地知道这一点!
  • 删除 .ready() 并将 click 更改为 change。复选框和单选按钮监听change 事件。编辑:演示jsfiddle.net/Palestinian/rEgAX/2

标签: javascript jquery jquery-mobile checkbox onclick


【解决方案1】:

你必须把你的代码放在里面

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

因为你的脚本在你的复选框被渲染之前出现。

编辑

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

应该是这样而不是.ready()函数:

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

【讨论】:

  • 现在工作正常!今天学到了新东西。 :D 谢谢!
  • 这是完全错误的,我不知道它是如何被接受和 3 票赞成的。 .ready() 不应该在 jQuery Mobile 中使用,为什么? stackoverflow.com/questions/14468659/…
  • @Omar 我很抱歉。我还没有尝试过 jQuery Mobile。我不知道他们有这种区别。无论如何,谢谢你,我今天也学到了一些新东西。哈哈
  • 将您的答案更改为 $(document).on('pageinit', function () { 并添加我提供的链接作为参考,除了此 api.jquerymobile.com/category/events 还通知 OP 更改。谢谢,祝你好运
【解决方案2】:

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

尝试将您的代码包装在:

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

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

【讨论】:

    猜你喜欢
    • 2020-11-10
    • 1970-01-01
    • 2017-04-05
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2019-11-27
    • 1970-01-01
    相关资源
    最近更新 更多