javascript JQuery:如何命名点击函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5197207/
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
JQuery: how to name click functions?
提问by sehummel
I have a script and I need to be able to name some of my anonymous click functions. For instance, here is some code:
我有一个脚本,我需要能够命名我的一些匿名点击函数。例如,这里有一些代码:
Document ready:
文件准备好:
$(function(){
$('#map').imagemap([
{top_x: 1,top_y: 2,bottom_x: 290,bottom_y:380,callback: #id1 anonymous function},
{top_x: 275,top_y: 2,bottom_x: 470,bottom_y:380,callback: #id2 anonymous function},
{top_x: 460,top_y: 2,bottom_x: 701,bottom_y:380,callback: #id3 anonymous function}
]);
$('#id1').click(function() {
....
});
$('#id2').click(function() {
....
});
$('#id3').click(function() {
....
});
...
});
How do I write my callbacks so that I don't have to duplicate the code outside the document.ready? I tried putting it all inline, following the callback:, but it didn't work. So what do I put in place of my anonymous function callback calls?
如何编写我的回调,以便我不必在document.ready?之外复制代码?我尝试将其全部内联,遵循callback:,但没有奏效。那么我用什么来代替匿名函数回调调用呢?
回答by JaredPar
It sounds like you want to have the clickfunctions use a named function which is callable from elsewhere in the code. If so just define the functions outside the jQuery ready function and use them by name in the clickmethod.
听起来您想让click函数使用可从代码中的其他地方调用的命名函数。如果是这样,只需在 jQuery 就绪函数之外定义函数并在click方法中按名称使用它们。
function id1Click() {
...
}
...
$(function() {
$('#id1').click(id1Click);
});
回答by Babak Naffas
Instead of using an anonymous function like in your example
而不是像您的示例中那样使用匿名函数
$('#id3').click(function() {
....
});
you can define your function elsewhere and use that function
您可以在别处定义您的功能并使用该功能
$('#id3').click(myClickCallback);
function myClickCallback{
...
}
回答by Ned Batchelder
function id1_click() { ... }
function id2_click() { ... }
function id3_click() { ... }
$(function(){
$('#map').imagemap([
{top_x: 1,top_y: 2,bottom_x: 290,bottom_y:380,callback: id1_click },
{top_x: 275,top_y: 2,bottom_x: 470,bottom_y:380,callback: id2_click },
{top_x: 460,top_y: 2,bottom_x: 701,bottom_y:380,callback: id3_click }
]);
$('#id1').click(id1_click);
$('#id2').click(id2_click);
$('#id3').click(id3_click);
...
});

