【问题标题】:JS event bubbling - How can I avoid the changing targets?JS 事件冒泡 - 如何避免目标不断变化?
【发布时间】:2023-01-19 15:58:14
【问题描述】:

我已将点击事件监听器绑定到上下投票按钮。

问题:当我点击按钮的不同部分时,我得到的是我点击的相应元素,而不是包含相关信息以供进一步处理的父元素。

我已经尝试过的:我已经尝试过 ev.stopPropagation(); 但行为保持不变。

问题:我怎么解决这个问题?

我的示例代码

const commentVotes = document.querySelectorAll('.comment-votes');

commentVotes.forEach((row) => {
  const up = row.querySelector('.comment-vote-up');
  const down = row.querySelector('.comment-vote-down');            

  up.addEventListener('click', async (ev) => {    
    // ev.stopPropagation();
    const id = ev.target.getAttribute('data-item-id');
    console.log({"target": ev.target, "ID": id})
  });
  
  down.addEventListener('click', async (ev) => {
    // same as up
  })
});
.comment .comment-vote-box {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.spacer {
  margin-right:10px;
}
<div class="comment">
  <div class="comment-vote-box comment-votes mt-10">
    
    <div class="vote-up">
      <button class="comment-vote-up"
              data-item-id="11">
        <span class="spacer">Like</span>
        <span>0</span>
      </button>
    </div>
    
    <div class="vote-down">
      <button class="comment-vote-down"
              data-item-id="12">
        <span class="spacer">Dislike</span>
        <span>1</span>
      </button>
    </div>
    
  </div>
</div><!-- comment -->

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    使用 Event.currentTarget 从中获取属性值。

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多