简体   繁体   English

将参数传递给jQuery ready()的解决方法

[英]Workaround for passing parameter to jQuery ready()

I have some code called on jQuery document.ready() which is used in multiple HTML files. 我在jQuery document.ready()上调用了一些代码,该代码在多个HTML文件中使用。 Now the difference is each of these HTMLs uses a different div id. 现在的区别是,每个HTML都使用不同的div ID。 I know one option is to just check for hardcode div ids inside $(document).ready() . 我知道一种选择是只检查$(document).ready()中的硬编码div ID。 But I wanted to write a generic code which would take the div Ids based on the currrent/calling HTML page? 但是我想编写一个通用代码,该代码将基于当前/调用HTML页面获取div ID?

So is there any way or workaround for passing parameter to jQuery ready() ? 那么有没有办法将参数传递给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() . $(document).ready()只需要一个函数作为参数,因此您可以编写一个将ID作为参数并返回$(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. 然后,您可以将make_ready放在某个公共位置,并使用它来构建$(document).ready()调用的函数。

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. 通过存储每个html的当前div ID,您仍然可以在文档准备功能中定义通用代码。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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