You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击事件首次点击不触发,二次点击正常?附代码求解答

Why Your Click Event Only Works on the Second Click

Hey there! Let's figure out why your click handler isn't behaving as expected. The issue here isn't that the event isn't firing on the first click—it actually is! The problem lies in what you're trying to remove.

The Root Cause: childNodes Includes Text Nodes

Your code uses iParent.childNodes[0] to target the element you want to delete. But childNodes returns all child nodes of an element, including invisible text nodes created by whitespace (like newlines or spaces) in your HTML.

On the first click, you're probably deleting one of these blank text nodes instead of the actual element you care about. Since there's no visible change, it feels like the event didn't run. By the second click, that text node is gone, so childNodes[0] now points to the element you intended to remove—hence the visible effect.

Fixes to Try

1. Use children Instead of childNodes

children only returns element nodes (skipping text nodes), so it'll target the actual DOM element you want to remove right away:

const btn = document.querySelectorAll('#container div i'); 
btn.forEach(function(btn){ 
  btn.addEventListener('click', function(e){ 
    const iParent = e.target.parentElement.parentElement; 
    iParent.removeChild(iParent.children[0]); 
  }); 
});

2. Use firstElementChild + remove() (Cleaner Approach)

A more modern and readable way is to use firstElementChild to directly grab the first element node, then call remove() on it. We've added a check to avoid errors if no child elements are left:

const btn = document.querySelectorAll('#container div i'); 
btn.forEach(function(btn){ 
  btn.addEventListener('click', function(e){ 
    const iParent = e.target.parentElement.parentElement; 
    if (iParent.firstElementChild) {
      iParent.firstElementChild.remove();
    }
  }); 
});

Either of these should make the click action work as expected on the first try!

内容的提问来源于stack exchange,提问作者JackCow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:38:46