javascript - 如何排除单个字段触发以整个表单(vanilla JS)注册的 onchange 事件?
问题描述
我有一个这样注册form
的onchange
事件:
<form onchange="myEventFunction();">
<select name="select1">options...</select>
<select name="select2">options...</select>
<select name="select3">options...</select>
</form>
这工作得很好,当一个人改变任何选择字段时,事件就会被触发。
但是如何配置其中一个选择以不触发 onchange 事件?或者,或者,我如何检查触发元素myEventFunction()
以便提前返回?
用例:更改表单应该通过重新加载搜索结果XmlHttpRequest
(这工作得很好)。但其中一个字段只是更改不同字段的选项,不应触发“提交”。我的实际表单比这个例子大得多,所以onchange
在除一个之外的每个字段上注册一个对我来说只是最后的“蛮力”解决方案。
解决方案
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>
推荐阅读
- dpdk - pktgen-dpdk !PANIC!: *** 没有找到要使用的端口 ***
- c++ - 在结构中分配数组字段
- python - 由极坐标方程给出的阵列掩模边界
- markdown - 目录网站的 Jekyll 收藏或类别选择?
- java - 如何在没有“超出范围”的 SQL 异常的情况下获取所有数据?
- sql-server - 为什么即使指定了模式绑定,视图也不绑定模式?
- mysql - Mysql容器错误,socket创建错误
- ruby-on-rails - 在 Rails 引擎中动态拦截和调用 Ruby on Rails 路由
- python-3.x - 如何设置一组地理轴 - 子图的 cartopy 网格线标签样式(major_xticks 和 minor_xticks)?
- arduino - 如何使用 MQTT 构建仅控制 ESP32 的内置 LED 开/关的 Arduino 草图?