简体   繁体   English

为什么事件委派ES6侦听器将输入的点击记录为按钮的点击?

[英]Why does event delegation ES6 listener track input clicks as button clicks?

I am not sure why when I want to listen for input clicks separate from button clicks it does not discriminate? 我不确定为什么当我要听输入的点击声与按钮的点击声分开时,为什么不能区分? I put the listener on the UL for this as the LIs are dynamically added (event delegation). 由于动态添加了LI(事件委托),因此我将侦听器放在UL上。 When you click on a checkbox it is recognized as a button. 当您单击复选框时,它将被识别为按钮。

function toggleDone(e) {
    if (!e.target.matches('button'))
    { return; }

Here is the js/html 这是js / html

 <li>
   <input type="checkbox" data-index="${i}" id="item${i}" 
${item.chosen ? 'checked' : ''} /> 
   <label for="item${i}">${item.text} </label>
   <button title="delete" id="del${i}">X</button>
 </li>

I hope this isn't too much of a newbie question, but I'd like to understand if I'm doing something wrong, or if it might be an actual bug. 我希望这不是一个新手问题,但是我想了解我是在做错什么,还是可能是一个实际的错误。

I am using e.target.localName instead of e.target and match instead of matches 我正在使用e.target.localName而不是e.targetmatch而不是matches

 let lis = Array.from(document.querySelectorAll("li")); lis.map((li) =>{ li.addEventListener("click", toggleDone ) }) function toggleDone(e) { //console.dir(e.target.localName) let str = e.target.localName; console.clear(); if (!str.match('button')) { console.log("KK") }else{console.log("OK")} } 
 <ul> <li> <input type="checkbox" data-index="1" id="item1" checked /> <label for="item1">item 1 text</label> <button title="delete" id="del1">X</button> </li> <li> <input type="checkbox" data-index="2" id="item2" /> <label for="item2">item 2 text</label> <button title="delete" id="del2">X</button> </li> <li> <input type="checkbox" data-index="3" id="item3" /> <label for="item3">item 1 text</label> <button title="delete" id="del3">X</button> </li> </ul> 

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

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