問題描述

我在 WordPress 插件中使用了一個簡單的 jQuery 腳本,它使用了一個這樣的 jQuery 包裝器:

$(document).ready(function(){

    // jQuery code is in here

});

我在 WordPress 儀錶板內調用這個腳本,並且在 jQuery 框架加載之後加載它。

當我檢查 Firebug 中的頁面時,我會不斷收到錯誤消息:

TypeError: $ is not a function

$(document).ready(function(){

我應該在這個函數中包裝腳本:

(function($){

    // jQuery code is in here

})(jQuery);

我有這個錯誤了很多次,不知道該怎麼處理。

任何幫助將不勝感激。

最佳解決方案

默認情況下,當您在 Wordpress 中排隊 jQuery 時,必須使用 jQuery,並且不使用 $(這是為了與其他庫兼容) 。

你的 function 的解決方案可以正常工作,或者你可以用其他方式加載 jQuery(但這在 Wordpress 中可能不是一個好主意) 。

如果您必須使用 document.ready,則實際上可以將 $傳遞到函數調用中:

jQuery(function ($) { ...

次佳解決方案

這應該解決它:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  var body = $( 'body' );
});

簡單地説,WordPress 可以運行自己的腳本,然後才能釋放 $ var,這樣它就不會與其他庫衝突。這是非常有意義的,因為 WordPress 用於各種網站,應用程序,當然還有博客。

從他們的文檔:

The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.

In the noConflict() mode, the global $ shortcut for jQuery is not available…

第三種解決方案

這個解決方案適用於我



    ;(function($){
        // your code
    })(jQuery);

將代碼移動到閉包中,並使用 $而不是 jQuery

我在 https://magento.stackexchange.com/questions/33348/uncaught-typeerror-undefined-is-not-a-function-when-using-a-jquery-plugin-in-ma 中找到了上述解決方案

經過掃蕩太多

第四種方案

你可以避免這樣的衝突

var jq=jQuery.noConflict();
jq(document).ready(function(){  
  alert("Hi this will not conflict now");
  jq('selector').show();
});

第五種方案

嘗試這個:

<script language="JavaScript" type="text/javascript" src="jquery/jquery.js"></script>
<script>
    jQuery.noConflict();
    (function ($) {
        function readyFn() {
            // Set your code here!!
        }

        $(document).ready(readyFn); 
    })(jQuery);

</script>

第六種方案

你必須通過 $ in function()

<script>
jQuery(document).ready(function($){

// jQuery code is in here

});
</script>

第七種方案

var $=jQuery.noConflict();

$(document).ready(function(){
    // jQuery code is in here
});

感謝 Ashwani Panwar 和 Cyssoo 的答案:https://stackoverflow.com/a/29341144/3010027

第八種方案

仔細檢查你的 jQuery 引用。你可能會不止一次地引用它,或者你早點調用函數 (在定義 jQuery 之前) 。您可以按照我的評論中的提到,並將任何 jQuery 引用放在文件的頂部 (在頭上),看看是否有幫助。

如果您使用 jQuery 的封裝,在這種情況下不會有幫助。請嘗試,因為我認為它更漂亮,更明顯,但如果沒有定義 jQuery,您將得到相同的錯誤。

最後… jQuery 當前沒有定義。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。