想在 ready jQuery 方法中使用函数
want to use functions within ready jQuery method
我有一个类似的问题 ,我的问题是关于如何访问 Web 浏览器控制台中的所有 JavaScript 功能,即使它们是在 window.onload = function() {// code and functions}
内,但这次我想用 jQuery:
做同样的事情
$(document).ready(function() {
// I want to access all the functions that are here in the web console
})
您可以使用与上一个问题相同的语法。只需将函数分配给 window
.
下面的例子说明了我的意思。请注意,您不需要 setTimeout()
,这只是为了在此处的示例中定义时自动执行 your_function()
。
$(document).ready(function() {
window.your_function = function(){
console.log("your function");
};
your_function();
});
// setTimeout() is needed because the $.ready() function was not executed when
// this code block is reached, the function(){your_function();} is needed because
// the your_function() is not defined when the code is reached
setTimeout(function(){
your_function();
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
注意2:如果没有充分的理由,我建议不要在$(document).ready()
中定义全局函数。您可以在外部定义函数,然后在 $(document).ready()
.
中调用它们
我有一个类似的问题 window.onload = function() {// code and functions}
内,但这次我想用 jQuery:
$(document).ready(function() {
// I want to access all the functions that are here in the web console
})
您可以使用与上一个问题相同的语法。只需将函数分配给 window
.
下面的例子说明了我的意思。请注意,您不需要 setTimeout()
,这只是为了在此处的示例中定义时自动执行 your_function()
。
$(document).ready(function() {
window.your_function = function(){
console.log("your function");
};
your_function();
});
// setTimeout() is needed because the $.ready() function was not executed when
// this code block is reached, the function(){your_function();} is needed because
// the your_function() is not defined when the code is reached
setTimeout(function(){
your_function();
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
注意2:如果没有充分的理由,我建议不要在$(document).ready()
中定义全局函数。您可以在外部定义函数,然后在 $(document).ready()
.