2014-01-17 50 views
0

是否有可能避免定義長整型函數兩次,而只是觸發已定義的函數連接到具有不同事件的不同委派選擇器?jQuery觸發事件附加到不同的委託選擇器?

$('#list').on('click', 'li .controls a:nth-child(1)', function(event) { 
    // many lines 
}); 

^

$('#list').on('dblclick', 'li .title a', function(event) { 
    // same set of lines 
    // so just trigger the above function instead? 
}); 
+0

注意不同的選擇+不同的事件,相同功能的內容。 –

回答

1

您可以多次聲明函數第一

var handler = function(event) { 
    // many lines 
}; 

然後將其綁定到不同的委託選擇

$('#list').on('click', 'li .controls a:nth-child(1)', handler); 
$('#list').on('click', 'li .title a', handler); 
0

使用逗號另一個選擇添加到您的事件

$('#list').on('click', 'li .controls a:nth-child(1), li .title a', function(event) { 
    // many lines         ^^^^^^^^^^^^^ here 
}); 
0

是的,這就是:

var handler = function(event) { 
    // ... 
}; 

$('#list').on('click', 'li .controls a:nth-child(1)', handler); 
$('#list').on('click', 'li .title a', handler); 

或者只是:

$('#list').on('click', 'li .controls a:nth-child(1), li .title a', function(event) { 
    // ... 
});