【问题标题】:Jquery head tags issueJquery头标签问题
【发布时间】:2012-07-31 21:16:22
【问题描述】:

我已经疯了好几个小时在我的网站上测试一些 jquery 脚本,但没有任何效果,而它可以在 Fiddles 上运行......

这就是我的:

然后我有一个如下脚本,但我无法让它工作!!!

<script type="text/javascript">
$(":checkbox").bind("click", function(event) {
    if ($(this).is(':checked')) {
        $(".itemBox:not(#" + $(this).val() + ")").hide();
        $(".itemBox[id='" + $(this).val() + "']").show();
    } else {
        $(".itemBox").show();
    }
});
</script>

【问题讨论】:

  • 您确定 jQuery 已正确加载到您的网站上吗?
  • 完全不确定它是否被正确加载,实际上部分帖子已被删除。我在头标签中有这个:'

标签: javascript jquery tags head


【解决方案1】:

您必须等待文档加载,然后才能将事件绑定到它。

jQuery 提供了一种简单的方法来做到这一点,calling the ready method on the document,并将所有代码放入该函数中:

jQuery(document).ready(function($) {
    // All of your code should go in this function
});

【讨论】:

    【解决方案2】:

    稍微清理一下代码,使用文档准备好在附加事件处理程序之前确保元素存在。

    jQuery( function() {  //wait for document to be ready
        //$(":checkbox").on("click", function (event)  //should really use on() if it is jQuery 1.7+
        $(":checkbox").bind("click", function (event) {  //bind is deprecated
            var cb = jQuery(this),
                items = $(".itemBox");
            if (cb.is(':checked')) {
                items.hide();
                $("#" + cb.val()).show();
            } else {
                items.show();
            }
            cb = items = null;
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 2020-02-17
      • 1970-01-01
      相关资源
      最近更新 更多