简体   繁体   English

Javascript - 如何获取触发事件的元素

[英]Javascript - How do I pick up which element fired an event

Using the sample code from W3schools I am trying to set up a single event handler that will fire when any of multiple 'input' elements in a form are changed.使用来自 W3schools 的示例代码,我试图设置一个事件处理程序,当表单中的多个“输入”元素中的任何一个发生更改时,该事件处理程序将触发。 After many attempts I have the following:经过多次尝试,我有以下几点:

 var s = document.getElementById("add_data"); document.getElementById("add_data").addEventListener("change", function() { field_check(p1, p2); });

located at the end of the HTML, and after the form is created.位于 HTML 的末尾,并在创建表单之后。
(add_data is the name of the form that contains many 'input' elements as children. What I want is to receive the name parameter As I understand it, p1 and p2 should contain the event and the name of the field that fired the event. Instead I get a reference error, "p1 is not defined" from the event handler. On search I have found many convoluted solutions to this question, some of which I don't understand, but none that actually solve my problem. What am I doing wrong? (add_data 是包含许多“输入”元素作为子元素的表单的名称。我想要的是接收 name 参数据我所知,p1 和 p2 应该包含事件和触发事件的字段的名称。相反,我从事件处理程序中收到了一个参考错误,“p1 未定义”。在搜索中,我发现了许多令人费解的解决方案,其中一些我不明白,但没有一个能真正解决我的问题。我是什么做错了吗?

You mean to do你的意思是做

var s = document.getElementById("add_data");
s.addEventListener("change", function(event) {
  field_check(event, event.target.name);
});

or even simpler甚至更简单

document.getElementById("add_data").addEventListener("change", field_check);

and have并且有

function field_check(event) {
  console.log(event.target.name);
}

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

相关问题 如何找到以编程方式触发的 Javascript 事件的起源? - How can I find the origin of a Javascript event which was fired programmatically? 如何发现触发事件的 DOM 元素并做出相应的行为 - How do I discover the DOM element that fired the event and behave accordingly 使用对象方法时如何获取触发事件的源元素 - How do you get the source element which fired an event when using an object method 如何获取触发javascript中的horizo​​nSwiper事件的当前元素ID? - How do I get the current element id which triggered horizonSwiper event in javascript? 我如何从php提取一个值,以通过javascript将其放入输入元素? - How can I pick up a value from php to put it into input-element via javascript? Javascript DOM,如何确定触发了哪个事件侦听器? - Javascript DOM, How to figure out which event listener fired? 如何检查任何地方是否触发了Javascript事件? - How do I check if any Javascript event has been fired, anywhere? 我怎么知道哪个元素激活了javascript中的点击事件? - How can i know which element activated a click event in javascript? 如何在JS Prototype中找到触发mouseout事件的元素? - How can I find the element that fired a mouseout event in JS Prototype? 如何在React的上层元素上触发事件? - How do I trigger an event on a higher-up element in React?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM