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

$(document).ready(function(){

    // jQuery code is in here

});

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

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

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

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

(function($){

    // jQuery code is in here

})(jQuery);

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

任何帮助都将不胜感激。


当前回答

用jQuery替换$ sign 是这样的:

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

其他回答

这个解决方案对我很有效

;(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上找到了上面的解决方案

...在寻找太多之后

这应该解决它:

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

简单地说,WordPress在你之前运行他们自己的脚本,他们发布了$ var,所以它不会与其他库冲突。这是完全有道理的,因为WordPress被用于各种各样的网站、应用程序,当然还有博客。

从他们的文档来看:

WordPress包含的jQuery库被设置为noConflict() 模式(参见wp-includes/js/jquery/jquery.js)。这是为了防止 与其他JavaScript库的兼容性问题 可以链接。 在noConflict()模式下,jQuery的全局$快捷方式不是 可用……

你必须传递$ in function()

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

// jQuery code is in here

});
</script>

用jQuery替换$ sign 是这样的:

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

此外,我发现了使用jQuery noConflict模式的好解决方案。

(function($){

  $(document).ready(function(){
      // write code here
  });

  // or also you can write jquery code like this

  jQuery(document).ready(function(){
      // write code here
  });

})(jQuery);

我在TryVary.com找到了这个解决方案。