命名 jQuery 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5451589/
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
Naming jQuery Functions
提问by switz
$(".song").live('click', function songClick() {
//do stuff
});
Can you name a function like above and then call it at a later point? I tried, but it didn't work. Do I have to pass an event to it?
你能像上面那样命名一个函数,然后在以后调用它吗?我试过了,但没有用。我是否必须将事件传递给它?
采纳答案by Liza Daly
Just name it as a standalone function and call it from live()
:
只需将其命名为独立函数并从live()
以下位置调用它:
function songClick() {
// do stuff
}
$(".song").live('click', songClick);
Note the lack of parens in the live()
method.
请注意该方法中缺少括号live()
。
回答by K.S.
Note for reference's sake:
请注意以供参考:
The live method was removed in version 9. Anyone coming across this question now should use on() instead. But otherwise, should work the same as above answers.
live 方法在版本 9 中被删除。现在遇到这个问题的任何人都应该使用 on() 代替。但除此之外,应该与上述答案相同。
function songClick() {
//code
}
$(".song").on('Click', songClick);
If you only want the event handler to run once you can also use one() as well.
如果您只希望事件处理程序运行一次,您也可以使用 one() 。
回答by Ernest Friedman-Hill
You can define the function beforethe jquery code, then just pass the name to jquery; i.e.,
你可以在jquery代码之前定义函数,然后把名字传给jquery;IE,
function songClick() {
//do stuff
}
$(".song").live('click', songClick);
You could then use songClick() elsewhere, too.
然后,您也可以在其他地方使用 songClick()。