How do I add a simple jQuery script to WordPress?

2018-12-31 20:11发布

I read the Codex and a few blog posts about using jQuery in WordPress, and its very frustrating. I've got as far as loading jQuery in functions.php file, but all of the guides out there are crappy because they assume you already have a ton of WordPress experience. For instance, they say that now that I'm loading jQuery through the functions.php file, now all I have to do is load my jQuery.

How exactly do I do this? What files, specifically, do I add code to? How exactly do I add it for a single WordPress page?

14条回答
时光乱了年华
2楼-- · 2018-12-31 20:44

There are many tutorials and answers here how to add your script to be included in the page. But what I couldn't find is how to structure that code so it will work properly. This is due the $ being not used in this form of JQuery.

So here is my code and you can use that as a template.

jQuery(document).ready(function( $ ){
  $("#btnCalculate").click(function () {
        var val1 = $(".visits").val();
        var val2 = $(".collection").val();
        var val3 = $(".percent").val();
        var val4 = $(".expired").val();
        var val5 = $(".payer").val();
        var val6 = $(".deductible").val(); 
        var result = val1 * (val3 / 100) * 10 * 0.25;
        var result2 = val1 * val2 * (val4 / 100) * 0.2;
        var result3 = val1 * val2 * (val5 / 100) * 0.2;
        var result4 = val1 * val2 * (val6 / 100) * 0.1;
        var val7 = $(".pverify").val();
        var result5 = result + result2 + result3 + result4 - val7;
        var result6 = result5 * 12;
        $("#result").val("$" + result);
        $("#result2").val("$" + result2);
        $("#result3").val("$" + result3);
        $("#result4").val("$" + result4);
        $("#result5").val("$" + result5);
        $("#result6").val("$" + result6);
  });
});
查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 20:45

**#Method 1:**Try to put your jquery code in a separate js file.

Now register that script in functions.php file.

function add_my_script() {
    wp_enqueue_script(
      'custom-script', get_template_directory_uri() . '/js/your-script-name.js', 
        array('jquery') 
    );
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );

Now you are done.

Registering script in functions has it benefits as it comes in <head> section when page loads thus it is a part of header.php always. So you don't have to repeat your code each time you write a new html content.

#Method 2: put the script code inside the page body under <script> tag. Then you don't have to register it in functions.

查看更多
登录 后发表回答