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 par开发者_JAVA技巧ameter 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
});
精彩评论