简体   繁体   English

我是否需要使用JQuery删除和替换事件处理程序以交换它们?

[英]Do I need to remove and replace event handlers with JQuery to swap them?

  1. I want the events click and touchstart to trigger a function. 我希望事件clicktouchstart触发功能。

Of course this is simple with JQuery. 当然,使用JQuery很简单。 $('#id').on('click touchstart', function{...});

  1. But then once that event is triggered, I want that same handler to do something else when the events are triggered, 但是一旦触发了该事件,当事件触发后,我希望同一个处理程序执行其他操作,

  2. and then later, I want to go back to the original handling function. 然后,我想回到原始的处理功能。

It seems like there must be a cleaner way to do this than using $('#id').off('click touchstart'); 与使用$('#id').off('click touchstart');相比,似乎必须有一种更清洁的方法$('#id').off('click touchstart'); and then re-applying the handler. 然后重新应用处理程序。

How should I be doing this? 我应该怎么做?

The way I would do this is by creating a couple of functions for the handler function to call based on certain flags. 我这样做的方式是通过为处理程序函数创建几个函数来基于某些标志进行调用。 Sudo code would be something like this: Sudo代码将如下所示:

function beginning_action() {
...
}

function middle() {
...
}

var beginning_state = true;    

$('#id').on('click touchstart', function{
  if(beginning_state) {
    beginning_action();
  } else {
    middle();
  }
});

Then all you need to do is change the variable beginning_state to change which function is called. 然后,您所需要做的就是更改变量beginning_state以更改调用哪个函数。 Of course you would give them better names that describe what they do and not when they do it. 当然,您可以给他们更好的名字来描述他们的工作,而不是描述他们的工作时间。

Additionally, if you want the handler to call more than two functions you can change the beginning_state variable from a boolean to an int and check it's value to determine which function to call. 另外,如果您希望处理程序调用两个以上的函数,则可以将beginning_state变量从布尔值更改为int并检查其值以确定要调用的函数。

Good luck! 祝好运!

You can create a counter variable in some construct in your javascript code that allows you to decide how you want to handle your event. 您可以在JavaScript代码的某些构造中创建一个计数器变量,该变量可让您决定如何处理事件。

  $(function() { var trackClicks = (function() { var clicks = true; var getClicks = function() { return clicks; }; var eventClick = function() { clicks = !clicks; }; return { getClicks: getClicks, eventClicks: eventClicks } })(); $('#id').on('click touchstart', function { if (trackClicks.getClicks()) { handler1(); } else { handler2(); } trackClicks.eventClick(); }); function handler1() { //firsthandler}; function handler2() { //secondhandler}; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM