jQuery 如何修复 WordPress 自定义页面中的“TypeError: $ is not a function”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18295538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:19:31  来源:igfitidea点击:

How to fix "TypeError: $ is not a function" error in WordPress custom page?

jqueryhtmlwordpress

提问by Radek

I created custom WordPress page via plugin where I want to toggle on/off comments using this code

我通过插件创建了自定义 WordPress 页面,我想在其中使用此代码打开/关闭评论

<script type="text/javascript">                 
  $("comment_switch").click(function () {
    $("comments").toggleClass("hidden");
  });
</script> 

I placed it inside the <body>tag. To generate <head>tag I used standard WordPress function wp_head();. When I check the source code of the page I can see in head section <script src="http://10.1.1.6/wp-includes/js/jquery/jquery.js?ver=1.10.2" type="text/javascript">which I thought would be enough to use jQuery.

我把它放在<body>标签里面。为了生成<head>标签,我使用了标准的 WordPress 功能wp_head();。当我检查页面的源代码时,我可以在 head 部分看到<script src="http://10.1.1.6/wp-includes/js/jquery/jquery.js?ver=1.10.2" type="text/javascript">我认为足以使用 jQuery。

Could someone help me to make the jQuery code work? The whole source code of the page could be found here

有人可以帮助我使 jQuery 代码工作吗?页面的整个源代码可以在这里找到

回答by Roko C. Buljan

You're probably missing some .class markup and the DOM ready function

您可能缺少一些.类标记和DOM 就绪函数

jQuery(function($) { // DOM is now ready and jQuery's $ alias sandboxed

    $(".comment_switch").click(function () {
        $(".comments").toggleClass("hidden");
    });

});

回答by DevZer0

you need to encapsulate your javascript in function that executes on DOM ready event

您需要将 javascript 封装在在 DOM 就绪事件上执行的函数中

<script type="text/javascript">                 
 $(function () {
   $("comment_switch").click(function () {
    $("comments").toggleClass("hidden");
  });
});
</script> 

回答by hamza omar

    <script type="text/javascript">                 
 (function () { // 1) remove the "$"
   $(".comment_switch").click(function () { // 2) add "." if this a class or "#" // if it is an id
    $(".comments").toggleClass("hidden");
  });
});
</script>