I am struggling on how to organise my jquery code.
我正在努力学习如何组织我的jquery代码。
I have the following functions:
我有以下功能:
function Function1() {
$('a').not('a.dialog').click(function(event){
// Do something.
});
};
function Function2() {
$('a.dialog').click(function () {
// Do something.
});
};
Function1 is called on every page, function2 is called only on a single page.
Function1在每个页面上都被调用,function2只在一个页面上调用。
What is the best way to remove the duplication between these two functions specifically the reference to 'a.dialog'.
要消除这两个函数之间的重复,最好的方法是引用“a.dialog”。
Should I be using global variables? or is the above code the best I can hope for?
我应该使用全局变量吗?或者以上代码是我所能期望的最好的?
------------------ UPDATE ------------------
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -更新
The specifics of the two functions are as follows:
这两项职能的具体情况如下:
Function1 does this: iPhone Safari Web App opens links in new window
Function1这样做:iPhone Safari Web应用程序在新窗口中打开链接。
Function2 opens a dialog lightbox.
Function2打开一个对话框lightbox。
2 个解决方案
#1
1
One way could be to do it like that :
一种方法是这样做:
$('a').click(function(){
alert('work');
})
$('.dialog').unbind().click(function(){
alert('really work')
})
Reduce the number of if...
减少if…
Fiddle : http://jsfiddle.net/SJvrD/
小提琴:http://jsfiddle.net/SJvrD/
#2
2
function Function1() {
$('a').click(function(event){
if($(this).is('.dialog')) //or .hasClass('dialog')
//...
else //...
});
};
#1
1
One way could be to do it like that :
一种方法是这样做:
$('a').click(function(){
alert('work');
})
$('.dialog').unbind().click(function(){
alert('really work')
})
Reduce the number of if...
减少if…
Fiddle : http://jsfiddle.net/SJvrD/
小提琴:http://jsfiddle.net/SJvrD/
#2
2
function Function1() {
$('a').click(function(event){
if($(this).is('.dialog')) //or .hasClass('dialog')
//...
else //...
});
};