JavaScript WordPress uncaught typeerror $ is not a

2019-09-19 15:00发布

问题:

$(document).ready(function(){
   $(".showhide").click(function(){
      $("nav").slideToggle("slow");
   });
});

I'm not a JavaScript programmer. I'm getting this error: Uncaught TypeError $ is not a function

For some reason my navigation is not working. Someone told me to put this in JavaScript but I'm getting the error.

Found this: jQuery(document); but don't know how to use this.

回答1:

This is how you should do it specially on WordPress (since Wordpress is usually using jQuery instead of $)

(function($){
  $(document).ready(function(){
   $(".showhide").click(function(){
      $("nav").slideToggle("slow");
   });
  });

})(jQuery);

Reference here

or if you don't like the answer above, you can add var $ = jQuery; before the $(document).ready function



回答2:

The issue is that WordPress uses jQuery in compatibility mode, which means that it does NOT utilize the $ by default.

You CAN use the $ to access jQuery, but you just need to wrap it in a document ready function.

Here's the simplest way to do this:

// By passing the $ as a function argument, $ is available anywhere inside this document ready function
jQuery(function($) {
   // Do all your $ jQuery goodness in here...
   $(".showhide").click(function(){
      $("nav").slideToggle("slow");
   });
   // $ is available until the end of the document ready
});
// Outside of the document ready function - now you cannot use $ - you'd have to use jQuery....
jQuery('.showhide').click(....);

For completeness sake, be sure you have enqueued jQuery.

In your theme's functions.php file, or in your plugin's main file, add this:

function theme_name_scripts() {
    wp_enqueue_script( 'jquery' );
}

add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

This ensures that jQuery is loaded - the right way - in your WordPress site.



回答3:

You should use jQuery instead of $ if you still gets the error do as following.

var j = jQuery.noConflict();

j(document).ready(function(){
   j(".showhide").click(function(){
      j("nav").slideToggle("slow");
   });
});