[英]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.