jQuery 如何从Jquery中的另一个函数调用一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18514504/
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
how to call a function from another function in Jquery
提问by user1911703
<script>
$(document).ready(function(){
//Load City by State
$('#billing_state_id').live('change', function() {
//do something
});
$('#click_me').live('click', function() {
//do something
//need to recall $('#billing_state_id').live('change', function() { but how?
});
});
</script>
Load City by State working fine but i don't know whether it's possible or not to call it within another function like $('#click_me').live('click', function()
.
按州加载城市工作正常,但我不知道是否可以在另一个函数中调用它,例如$('#click_me').live('click', function()
.
回答by Jason P
I assume you don't want to rebind the event, but call the handler.
我假设您不想重新绑定事件,而是调用处理程序。
You can use trigger()
to trigger events:
您可以使用trigger()
来触发事件:
$('#billing_state_id').trigger('change');
If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:
如果您的处理程序不依赖于事件上下文并且您不想为该事件触发其他处理程序,您还可以命名该函数:
function someFunction() {
//do stuff
}
$(document).ready(function(){
//Load City by State
$('#billing_state_id').live('change', someFunction);
$('#click_me').live('click', function() {
//do something
someFunction();
});
});
Also note that live()
is deprecated, on()
is the new hotness.
另请注意,live()
已弃用,on()
是新的热点。
回答by collapsar
wrap you shared code into another function:
将您共享的代码包装到另一个函数中:
<script>
function myFun () {
//do something
}
$(document).ready(function(){
//Load City by State
$(document).on('change', '#billing_state_id', function() {
myFun ();
});
$(document).on('click', '#click_me', function() {
//do something
myFun();
});
});
</script>
回答by ganji
I think in this case you want something like this:
我认为在这种情况下你想要这样的东西:
$(window).resize(resize=function resize(){ some code...}
Now u can call resize() within some other nested functions:
现在你可以在其他一些嵌套函数中调用 resize() :
$(window).scroll(function(){ resize();}