简体   繁体   中英

when calling javasript file not working in Wordpress

I called up javascript file with name 'main.js' but it isn't working. I inspected the file in chrome but was empty.can you help me, please

this is the javascript file below

$(document).ready(function(){
    alert('hello');
});

this is the functions file

<?php 
    function add_style(){
        wp_enqueue_style('bootstrap-css', "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css");
        wp_enqueue_style('font-awesome', get_template_directory_uri() . '/css/font-awesome.min.css');
        wp_enqueue_style('main-css', get_template_directory_uri() . '/css/main.css');
    }

    function add_script(){
        wp_enqueue_script('jquery', 'https://code.jquery.com/jquery-3.5.1.min.js');
        wp_enqueue_script('bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js', array('jquery'));
        wp_enqueue_script('html5shiv', get_template_directory_uri() . '/js/html5shiv.js');
        wp_enqueue_script('html5shiv', get_template_directory_uri() . '/js/html5shiv.js');
        wp_script_add_data('html5shiv', 'conditional', 'lt IE 9');
        wp_enqueue_script('respond', get_template_directory_uri() . '/js/respond.min.js');
        wp_script_add_data('respond', 'conditional', 'lt IE 9');
        wp_enqueue_script('main', get_template_directory_uri() . '/js/main.js');
    }
    function add_navbar(){

        register_nav_menus(array(
            'navbar-menu' => 'navbar menu',
            'footer-menu' => 'footer menu'
        ));
    }
    function bootstrap_menu(){
        wp_nav_menu(array(
            'theme_location' => 'navbar-menu',
            'menu_class' => 'navbar-nav mr-auto'
        ));
    }
    add_action('wp_enqueue_scripts', 'add_style');
    add_action('wp_enqueue_scripts', 'add_script');
    add_action('init', 'add_navbar');
  1. You don't need to enqueue jQuery, it's already added in WordPress. You can find a list of libraries included in WordPress in the WordPress documentation .
  1. $ is not supported by default while using jQuery with WordPress.
    You can use one of the following methods to use $ with jQuery

(function($) {
    // $ Works! You can test it with next line if you like
    // console.log($);
})( jQuery );

OR

jQuery(document).ready(function( $ ) {
    // $ Works! You can test it with next line if you like
    // console.log($);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM