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

Add click event after another click event

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

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

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.");
}

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

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

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

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

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.");
    });
  }
}

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

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

并使用此代码:

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.");
    });
  }
}

尝试使用 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>