[英]Is there a way to trigger a jquery function if document.ready OR if an element is clicked?
I have a function that fires an ajax call when the page is initially loaded, but I want to be able to fire that same ajax call if my user clicks a 'refresh' button on the page.我有一个 function 会在页面最初加载时触发 ajax 调用,但我希望能够触发相同的 ajax 调用如果我的用户在页面上调用按钮。 Currently I accomplish this by having two completely separate (but identical) functions.
目前,我通过拥有两个完全独立(但相同)的功能来实现这一点。 One fires on
$(document).ready(
and the other fires on $(document).on('click'
一个触发
$(document).ready(
另一个触发$(document).on('click'
Any way to consolidate these so it's just one function that gets fires on either document.ready OR document.on'click'?有什么方法可以整合这些,所以它只是一个 function 在 document.ready 或 document.on'click' 上触发?
Simply define it and pass it as an argument.只需定义它并将其作为参数传递。
function func () {}
$(document).ready(func); // or $(func)
$(document).on("click", ".your-btn", func);
You can also define a variable and assign your function to it as an expression.您还可以定义一个变量并将您的 function 作为表达式分配给它。 Then, call it immediately and use wherever you want.
然后,立即调用它并在任何你想要的地方使用。
$(document).ready(function() {
let foo;
(foo = function() {
console.log('Foo');
})();
$(document).on('click', '<selector>', foo); // $('<selector>').click(foo);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.