如何将事件委托添加到单选按钮上的“更改”事件(而不是单击)?

问题描述 投票:0回答:1
javascript performance dom event-handling event-delegation
1个回答
0
投票
您可以使用

input

 事件,该事件对任何表单元素也有效

演示:

const myForm = document.forms['my-form']; myForm.addEventListener('submit', e => { e.preventDefault(); // disable submit - page reload const formValues = Object.fromEntries(new FormData(myForm).entries()); console.log( formValues ); setInterval(console.clear,8000); }) myForm.addEventListener('input', e => { if (!e.target.matches('input[type="radio"]')) return; console.log(myForm['difficulty-ask'].value); setInterval(console.clear,2000); });
label    { display:block; }
fieldset { width: fit-content; }
<form name="my-form">
  <fieldset>
    <legend> difficulty </legend>
    <label>
      <input name="difficulty-ask" type="radio" value="all" checked >
      All
    </label>
    <label>
      <input name="difficulty-ask" type="radio" value="easy" >
      Easy
    </label>
    <label>
      <input name="difficulty-ask" type="radio" value="medium" >
      Medium
    </label>
    <label>
      <input name="difficulty-ask" type="radio" value="hard" >
      Hard
    </label>
  </fieldset>
  <button>submit</button>
</form>

© www.soinside.com 2019 - 2024. All rights reserved.