简体   繁体   中英

How do I tie in jQuery code onto certain pages?

I have a Wordpress based site (which I think is irrelevent to this question, but I'm putting it out there in case it impacts the answers).

And I want to keep javascript out of the page/post content. I'm introducing some jQuery functionality for form validation on a few different pages, and I'm trying to keep my javascript together in one file.

The theme I'm using lets me tick off a checkbox to include jQuery, and then I have a footer script block which pulls in my custom javascript for the site.

When the page is ready, I want to run the javascript to customize each of the special pages with their code using jQuery to hook up the event/validation code.

I'm currently doing it like this:

jQuery(document).ready(function($) {
    el = $('#myhelpform'); 
    if (el.length > 0)
    {  
        myhelpform(el);
    }

    el = $('#pkform');
    if (el.length > 0)
    {
        pkform(el);
    }

    el = $('.buynowreceipt')
    if (el.length > 0)
    {
        ...
    }      
});  // ready

...keeping the specific functionality in different functions, but I'm wondering if this is the way to go. I'm a javascript/jQuery noob.

Is my example above the best/only way to do this and if not, how would you solve the problem?

UPDATE: To clarify my question a bit

This is not question about how to load scripts conditional on certain pages. It's about having a single js file that gets downloaded once, is in the cache, but not has to run certain page specific stuff based on the body class of the page or the existence of a form on a page, or something else.

For example, I recently learned an alternative to my code above would be to do this:

jQuery(document).ready(function($) {
    el = $('#myhelpform'); 
    if (el.length > 0)
    {  
        myhelpform(el);
    }
});


jQuery(document).ready(function($) {
    el = $('#pkform');
    if (el.length > 0)
    {
        pkform(el);
    }
});

jQuery(document).ready(function($) {
    el = $('.buynowreceipt')
    if (el.length > 0)
    {
        ...
    }      
});

I'm just trying to learn how to do it right the first time.

And Thank You to Obmerk for having explained conditionally loading scripts in Wordpress the correct way.

I have a Wordpress based site (which I think is irrelevent to this question, but I'm putting it out there in case it impacts the answers).

It is in fact relevant, because then You should use wp_register_script() and wp_enqueue_script() ..

Those function in wordpress will allow you to correctly register the functions , and allow also an easy filtering to WHERE you want the scripts to register , and also provide and easy way to separate Admin side scripts and regular front side ones . This is the correct way to load scripts in wordpress and also filter their appearance .

The enqueue mechanisem will also take care of any dependencies and will ensure your script is loaded only after such dependencies ( jQuery for example )

like so ( ADMIN AREA ):

add_action('admin_enqueue_scripts', 'o99_cfsa_admin_load_scripts');

function o99_cfsa_admin_load_scripts($hook){ // notice the HOOK for admin pages

if( $hook != 'widgets.php' ) // this will load only on widgets pages admin 
        return;
// in this example , the chosen_k script will not load before the dependecies (first jquery, then chosen , then custom chosen_k script..)
    wp_enqueue_script('chosen', plugins_url( '/js/chosen.jquery.js', __FILE__ ), array('jquery'),'099',TRUE); 
    wp_enqueue_script('chosen_k', plugins_url( '/js/k99.chosen.init.js', __FILE__ ), array('jquery','chosen'),'099',TRUE); 
    wp_enqueue_style('chosencss', plugins_url( '/js/chosen.css', __FILE__ ), array(),'all'); 

}

That example is for the admin side , but to use it on the front side , you just need to use a different action :

        add_action('enqueue_scripts', 'o99_cfsa_load_scripts'); // Different action

    function o99_cfsa_load_scripts(){ 

    if( is_front_page() ) // example : this will load on all EXCEPT front page 
            return;
    // in this example , the chosen_k script will not load before the dependecies (first jquery, then chosen , then custom chosen_k script..)
        wp_enqueue_script('chosen', plugins_url( '/js/chosen.jquery.js', __FILE__ ), array('jquery'),'099',TRUE); 
        wp_enqueue_script('chosen_k', plugins_url( '/js/k99.chosen.init.js', __FILE__ ), array('jquery','chosen'),'099',TRUE); 
        wp_enqueue_style('chosencss', plugins_url( '/js/chosen.css', __FILE__ ), array(),'all');
} 

This will allow you to easily control the pages also on the front-end with simple wp conditional tags :

 if ( is_front_page() ) {
wp_enqueue_script('chosen', plugins_url( '/js/chosen.jquery.js', __FILE__ ), array('jquery'),'099',TRUE);
}

or in your case

 if ( is_single( array( 17, 19, 1, 11 ) )  ) { // array of your single posts ID´s 
wp_enqueue_script('chosen', plugins_url( '/js/chosen.jquery.js', __FILE__ ), array('jquery'),'099',TRUE);
}

or even

is_page( 'my-page' ) // for pages, using slug . see the conditional tags .

Note that it is always better to first register, and then enqueue the scripts . ( read the documentation of the functions linked above )

See more info here :

http://scribu.net/wordpress/optimal-script-loading.html

http://www.paulund.co.uk/add-stylesheets-to-wordpress-correctly

or just search google for "correctly load javascript wordpress "

Another way , much less recommended would be to use the wp_footer and wp_head actions to directly print your scripts ( but again, not the best practice ):

    function your_script_print_function() {
if ( is_single( array( 17, 19, 1, 11 ) )  ){
        echo '<script type="text/javascript">

            // <![CDATA[

                jQuery(document).ready(function() {
                           // your script here ..
                });

            // ]]>

        </script>'; 
}
    }
    add_action('wp_footer', 'your_script_print_function', 100); // or wp_head

Just use .each() ( info ):

$('#myhelpform').each(function( index ) {
    // do stuff
});

If you want to separate out into functions I think you have to wrap your function call inside the each function, like this:

$('#myhelpform').each(function( index ) {
    myhelpform(this);
});

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