2012-08-02 77 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; 
    }); 
});