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

$(document).ready(function(){

    // jQuery code is in here

});

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

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

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

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

(function($){

    // jQuery code is in here

})(jQuery);

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

任何帮助都将不胜感激。


当前回答

对我有用的方法。要导入的第一个库是查询库,然后调用jQuery.noConflict()方法。

<head>
 <script type="text/javascript" src="jquery.min.js"/>
 <script>
  var jq = jQuery.noConflict();
  jq(document).ready(function(){
  //.... your code here
    });
 </script>

其他回答

这个解决方案对我很有效

;(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 $=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/

<script>
var jq=jQuery.noConflict();
(function ($) 
    {
    function nameoffunction()
    {
        // Set your code here!!
    }

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

现在用jq代替jQuery

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

试试这个:

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