解决WordPress插件中使用jQuery代码,控制台报错$ is not a function的问题

图片[1]-解决WordPress插件中使用jQuery代码,控制台报错$ is not a function的问题-不止主题

问题:

在一个 WordPress 的插件中,调用 jQuery 方法如下:

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

上述代码是在 WordPress 的仪表盘中调用的,而且是在 jQuery 后面引入的。 当通过FireBug查看时,控制台报错信息如下:

TypeError: $ is not a function
$(document).ready(function(){

这种情况应该怎么处理?

解答:

默认情况下,当您在 WordPress 中按序引入 jQuery 时,您必须使用 jQuery,并且不使用 $(这是为了与其他库兼容)。 如果您必须使用 document.ready,则可以将 $ 传递给函数调用:

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…

其它JS代码示例:

var jq=jQuery.noConflict();
jq(document).ready(function(){  
  alert("Hi this will not conflict now");
  jq('selector').show();
});
;(function($){
    // your code
})(jQuery);
<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>

本文来源:https://www.manzj.net/topic/5a706f4d8047a60169661056

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容