2012-08-02 93 views
0

我已经疯了小时的测试在我的网站,并没有一些jQuery的脚本是工作,而这将在拨弄工作...jQuery的head标签问题

所以这是我在我的:

然后我有一个脚本如下,但我不能得到它的工作!

<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> 
+0

你能告诉我们小提琴吗? – 2012-08-02 20:33:31

+1

你确定jQuery在你的网站上正确加载了吗? – John 2012-08-02 20:34:27

+0

不知道它是否正确加载,实际上部分帖子被删除。我有这个头标签: '' – samyb8 2012-08-02 21:01:05

回答

5

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

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

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

整理了一下代码,使用文档准备,以确保该元素是存在的在附加事件处理程序之前。

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; 
    }); 
});