我有一个类似的问题之前,我的问题是如何访问所有的JavaScript函数在web浏览器控制台,即使他们是在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()
中调用它们。