如何通过ID单击单选按钮来激活事件?

时间:2019-02-07 16:14:37

标签: javascript css

我希望在通过其ID选择特定单选按钮时触发一个事件。无法正常工作,任何建议将不胜感激

if (event.target.id === "alarmManagRadios2") {
  alert("hi");
}
<body>
  <input type="radio" name="alarmManagRadios" id="alarmManagRadios1" value="ALARM" checked="">
  <br>
  <div for="alarmManagRadios1">
    Alarm
  </div>
  <input type="radio" name="alarmManagRadios" id="alarmManagRadios2" value="TEST">
  <br>
  <div for="alarmManagRadios2">
    Test
  </div>
</body>

2 个答案:

答案 0 :(得分:3)

在通过元素本身的无线电广播中调用函数,并在该函数中与单选按钮的ID相比较

function a(ele)
{
console.log(ele)
if (ele.getAttribute('id') === "alarmManagRadios2") {
  alert("hi");
}

}
<body>
  <input type="radio" onchange="a(this)" name="alarmManagRadios" id="alarmManagRadios1" value="ALARM" checked="">
  <br>
  <div for="alarmManagRadios1">
    Alarm
  </div>
  <input type="radio"  onchange="a(this)" name="alarmManagRadios" id="alarmManagRadios2" value="TEST">
  <br>
  <div for="alarmManagRadios2">
    Test
  </div>
</body>

答案 1 :(得分:2)

获取所有单选按钮并遍历集合并向其中添加事件。更改时,检查单击元素的ID。

document.getElementsByName将给出一个集合并使用数组方法forEach ...

[...document.getElementsByName('alarmManagRadios')].forEach((item) => {

  item.addEventListener('change', (e) => {
    if (event.target.id === "alarmManagRadios2") {
      alert("hi");
    }
  })
})
<input type="radio" name="alarmManagRadios" id="alarmManagRadios1" value="ALARM" checked="">
<br>
<div for="alarmManagRadios1">
  Alarm
</div>
<input type="radio" name="alarmManagRadios" id="alarmManagRadios2" value="TEST">
<br>
<div for="alarmManagRadios2">
  Test
</div>

如果浏览器支持,您也可以使用Array.from

Array.from(document.getElementsByName('alarmManagRadios')).forEach((item) => {

  item.addEventListener('change', (e) => {
    if (event.target.id === "alarmManagRadios2") {
      alert("hi");
    }
  })
})
<input type="radio" name="alarmManagRadios" id="alarmManagRadios1" value="ALARM" checked="">
<br>
<div for="alarmManagRadios1">
  Alarm
</div>
<input type="radio" name="alarmManagRadios" id="alarmManagRadios2" value="TEST">
<br>
<div for="alarmManagRadios2">
  Test
</div>