使用 JQuery 手动调用事件函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6959593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manually Calling an event function using JQuery
提问by Idan Shechter
I want to know if their is an option to call a function that is already assigned to a JQuery event.
我想知道他们是否可以选择调用已分配给 JQuery 事件的函数。
For example:
例如:
$("#somediv").change(function() { //do something });
$("#somediv").change(function() { //do something });
I want to be able to manually call that function that was originally assigned to the "somediv" element.
我希望能够手动调用最初分配给“somediv”元素的函数。
Thanks.
谢谢。
回答by Matt Ball
Have you tried this?
你试过这个吗?
$("#somediv").change();
回答by Jacob Mattison
JQuery can trigger a given event; just call $("#somediv").change()
.
JQuery 可以触发给定的事件;只是打电话$("#somediv").change()
。
回答by Guttsy
I think what you meant to do is define the function outside change(..).
我认为你的意思是在 change(..) 之外定义函数。
function whatever() { // do something }
$("#somediv").change(whatever);
Then you can call your function elsewhere.
然后你可以在别处调用你的函数。
At least that's how I interpreted your question.
至少我是这样解释你的问题的。
回答by Arvid Janson
A simple way of achieving this is placing the "actual" function outside the Jquery call. So, your code would look something like:
实现此目的的一种简单方法是将“实际”函数置于 Jquery 调用之外。所以,你的代码看起来像:
$("#somediv").change(function() { doSomething(); });
var doSomething = function() {
// actually do something
}
This would make it quite simple to call the doSomething function form anywhere in your scripts.
这将使在脚本中的任何位置调用 doSomething 函数变得非常简单。
回答by scottheckel
If you don't want to actualy trigger the change event (as shown in the previous answers above), you should probably extract that function into something that you can call from multiple places. It looks like you have found a place where reuse is in your application and extracting it may be the best answer.
如果您不想实际触发更改事件(如上面的先前答案所示),您可能应该将该函数提取到可以从多个位置调用的内容中。看起来您已经找到了在您的应用程序中重用的地方,提取它可能是最好的答案。
回答by Ancoor D Banerjee
<script type="text/javascript">
window.onload = function () {
$("#somediv").change();
}
</script>
i think this what you want to do .
我想这就是你想要做的。