首页 > 解决方案 > 如何排除单个字段触发以整个表单(vanilla JS)注册的 onchange 事件?

问题描述

我有一个这样注册formonchange事件:

<form onchange="myEventFunction();">
    <select name="select1">options...</select>
    <select name="select2">options...</select>
    <select name="select3">options...</select>
</form>

这工作得很好,当一个人改变任何选择字段时,事件就会被触发。

但是如何配置其中一个选择以触发 onchange 事件?或者,或者,我如何检查触发元素myEventFunction()以便提前返回?

用例:更改表单应该通过重新加载搜索结果XmlHttpRequest(这工作得很好)。但其中一个字段只是更改不同字段的选项,不应触发“提交”。我的实际表单比这个例子大得多,所以onchange在除一个之外的每个字段上注册一个对我来说只是最后的“蛮力”解决方案。

标签: javascripthtml

解决方案


You could pass the event argument and check against the event.target's name property:

function myEventFunction(event) {
  if (event.target.name == "select2") {
    event.preventDefault();
  } else {
    console.log('changed');
  }
}
<form onchange="myEventFunction(event)">
  <select name="select1">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
  </select>
  <select name="select2">
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>
  <select name="select3">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
  </select>
</form>


推荐阅读