简体   繁体   中英

Workaround for passing parameter to jQuery ready()

I have some code called on jQuery document.ready() which is used in multiple HTML files. Now the difference is each of these HTMLs uses a different div id. I know one option is to just check for hardcode div ids inside $(document).ready() . But I wanted to write a generic code which would take the div Ids based on the currrent/calling HTML page?

So is there any way or workaround for passing parameter to jQuery ready() ?

$(document).ready() just wants a function as an argument so you can write a function that takes your ID as an argument and returns a function for $(document).ready() . For example, instead of this:

$(document).ready(function() {
    $('#some_id').click(/*...*/);
});

you could do this:

function make_ready(id) {
    return function() {
        $('#' + id).click(/*...*/);
    };
}

$(document).ready(make_ready('some_id'));

Then you could put your make_ready in some common location and use it to build the functions for your $(document).ready() calls.

document ready just takes in an handler function as a parameter. You can still define a generic code in you document ready function, by storing the current div id for each html.

<input type="hidden" id="current_div" value="div1" />

$(document).ready(function() {  
    var div_id = $('#current_div').val();  
    // generic code  
});  

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