我在WordPress插件中有一个简单的jQuery脚本,它使用jQuery包装器,像这样:

$(document).ready(function(){

    // jQuery code is in here

});

我从WordPress仪表板内调用这个脚本,并在jQuery框架加载后加载它。

当我在Firebug中检查页面时,我不断地收到错误消息:

$不是一个函数 $(文档)时函数(){

我是否应该在这个函数中包装脚本:

(function($){

    // jQuery code is in here

})(jQuery);

我有这个错误相当多次,我不知道如何处理它。

任何帮助都将不胜感激。


当前回答

这个解决方案对我很有效

;(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();
});
(function( $ ) {
  "use strict";

  $(function() {

    //Your code here

  });

}(jQuery));
var $=jQuery.noConflict();

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

感谢Ashwani Panwar和Cyssoo回答:https://stackoverflow.com/a/29341144/3010027

在WordPress中使用jQuery而不是$的原因:https://pippinsplugins.com/why-loading-your-own-jquery-is-irresponsible/

用jQuery替换$ sign 是这样的:

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

当函数名和文件中的某个id名相同时,就会遇到这个问题。只要确保文件中所有的id名称都是唯一的。