2014-01-17 49 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) { 
    // ... 
});