在不同事件处理程序之间重用代码 [英] Reusing code between different event handlers
本文介绍了在不同事件处理程序之间重用代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个代码块,我想在不同的情况下触发单击,这取决于事件是直接事件还是委派.
I have one code block which I want to invoke in different scenarios when a click is triggered, depending on whether the event is direct or is delegated.
但是将代码更改为on
时,它只能部分起作用.
But on changing the code to on
, it only works partially.
我有一个代码:
$(document).on('click','.selected-option',function(event){
//lot of code
我要使用:
$('.selected-option').click(function(event){ //lots of code }
我想像这样一起使用
if (some condition)
{
$(document).on('click','.selected-option',function(event){
}
else
{
$('.selected-option').click(function(event){
}
,并希望使用相同的代码.
and want to use the same code.
推荐答案
您没有使用匿名函数来处理事件.只需编写一个常规函数:
You don't have to use anonymous functions to handle events. Just write a regular function:
function handleClick(event) {
// lots of code
}
然后将函数绑定到任意数量的事件:
Then bind the function to as many events as you want:
if (some condition) {
$(document).on('click','.selected-option', handleClick);
else {
$('.selected-option').click(handleClick);
}
这篇关于在不同事件处理程序之间重用代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文