使用自定义附加数据创建 JavaScript 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9071485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:30:50  来源:igfitidea点击:

JavaScript Event creation with customly attached data

javascriptjavascript-eventsevent-handling

提问by Alp

Is there a JavaScript way to pass custom data to a manually created JavaScript event?

有没有一种 JavaScript 方法可以将自定义数据传递给手动创建的 JavaScript 事件?

Ok, let's say I got this code to create and trigger a JavaScript event:

好的,假设我得到了这段代码来创建和触发一个 JavaScript 事件:

var evObj = document.createEvent('HTMLEvents');
evObj.initEvent('submit', bubbling, cancelable);
anElement.dispatchEvent(evObj);

This works fine and can be handled by using this code:

这工作正常,可以使用以下代码处理:

document.addEventListener('submit', mySubmitEventHandler, true);

But, I need a way to pass additional data to the event, so that mySubmitEventHandlerknows whether the event was fired by a user or by JavaScript event creation as shown above. A boolean value would be sufficient.

但是,我需要一种将额外数据传递给事件的方法,以便mySubmitEventHandler知道事件是由用户触发还是由 JavaScript 事件创建触发,如上所示。一个布尔值就足够了。

So, how can I add something like "myEvent = true" to the newly created evObj?

那么,如何向新创建的evObj.

And please no jQuery answers, I need to do this one in pure JavaScript.

并且请不要使用 jQuery 答案,我需要用纯 JavaScript 来做这个。

回答by Rob W

Attach the parameter to evObj.

将参数附加到evObj.

evObj.flag = 'Hi!';
anElement.dispatchEvent(evObj);

This code demonstrates that the event object passed by dispatchEventis equal to the one in the event listener (Live demo):

此代码演示传递的事件对象dispatchEvent等于事件侦听器中的事件对象(现场演示):

var evObj = document.createEvent('HTMLEvents');
document.body.addEventListener('test', function(e){ alert(e === evObj); },true);
evObj.initEvent('test', true, true);
document.body.dispatchEvent(evObj); // Shows alert, "true"

回答by wezzy

your evObj it's a normal object you can add any data as a property of the object like evObj.myData = "blablabla"; and then read the data in the listener

您的 evObj 它是一个普通对象,您可以添加任何数据作为对象的属性,例如 evObj.myData = "blablabla"; 然后读取监听器中的数据

Hope this helps

希望这可以帮助