How to fix “TypeError: $ is not a function” error

2020-02-06 02:11发布

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

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

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

3条回答
Animai°情兽
2楼-- · 2020-02-06 02:51

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

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

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

});
查看更多
Summer. ? 凉城
3楼-- · 2020-02-06 02:51

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

<script type="text/javascript">                 
 $(function () {
   $("comment_switch").click(function () {
    $("comments").toggleClass("hidden");
  });
});
</script> 
查看更多
Melony?
4楼-- · 2020-02-06 02:51
    <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> 
查看更多
登录 后发表回答