javascript 在另一个点击事件之后添加点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33262256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:17:11  来源:igfitidea点击:

Add click event after another click event

javascriptonclickonclicklistenerdom-events

提问by Alexander Weihmayer

I am trying to add a click event to the document in another click event attached to a button. However, the second click event is fired right away as if the event overlaps. I looked into stopping propagation, using a timeout, removing the listener, preventDefault(), but I've had no success.

我试图在附加到按钮的另一个单击事件中向文档添加一个单击事件。但是,第二个点击事件会立即触发,就好像事件重叠一样。我研究了停止传播,使用超时,删除侦听器preventDefault(),但我没有成功。

This is an example of what I am trying to do.

这是我正在尝试做的一个例子。

document.getElementById("test").addEventListener('click', first);

function first(){
    document.addEventListener('click', second);
}
function second(){
    alert("I'm not suppose to appear after the first click, only the second.");
}

For testing, I am using a simple button

为了测试,我使用了一个简单的按钮

<button type="button" id="test">Click</button>

I am doing this without JQuery. Is this possible?

我在没有 JQuery 的情况下这样做。这可能吗?

回答by guest271314

Try using event.stopImmediatePropagation()

尝试使用 event.stopImmediatePropagation()

document.getElementById("test").addEventListener('click', first);

function first(e){
    e.stopImmediatePropagation();
    this.removeEventListener("click", first);
    document.onclick = second;
}
function second(){
    alert("I'm not suppose to appear after the first click, only the second.");
}
<button type="button" id="test">Click</button>

回答by valepu

You can use a variable that keeps count of the clicks done

您可以使用一个变量来记录完成的点击次数

document.getElementById("test").addEventListener('click', clickHandler);

var clickCount=0;
function clickHandler(event){
  clickCount++;
  if(clickCount==2){
    event.target.removeEventListener("click");
    document.addEventListener('click', function(){
      alert("I'm not suppose to appear after the first click, only the second.");
    });
  }
}

If you don't want to use a global variable you can use dataset, make a button with this:

如果你不想使用全局变量,你可以使用数据集,用这个做一个按钮:

<button type="button" id="test" data-clickcount="0">Click</button>

And use this code:

并使用此代码:

document.getElementById("test").addEventListener('click', clickHandler);

function clickHandler(event){
  event.target.dataset.clickcount++;
  if(event.target.dataset.clickcount==2){
    event.target.removeEventListener("click");
    document.addEventListener('click', function(){
      alert("I'm not suppose to appear after the first click, only the second.");
    });
  }
}