如何在 JavaScript 中触发事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2490825/
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
How to trigger event in JavaScript?
提问by KoolKabin
I have attached an event to a text box using addEventListener. It works fine. My problem arose when I wanted to trigger the event programmatically from another function.
我已使用 将事件附加到文本框addEventListener。它工作正常。当我想从另一个函数以编程方式触发事件时,我的问题就出现了。
How can I do it?
我该怎么做?
采纳答案by Alsciende
You can use fireEventon IE 8or lower, and W3C's dispatchEventon mostother browsers. To create the event you want to fire, you can use either createEventor createEventObjectdepending on the browser.
您可以在IE 8或更低版本上使用fireEvent,在大多数其他浏览器上使用W3C 的dispatchEvent。要创建要触发的事件,您可以使用或取决于浏览器。createEventcreateEventObject
Here is a self-explanatory piece of code (from prototype) that fires an event dataavailableon an element:
这是一段不言自明的代码(来自原型),它dataavailable在 上触发事件element:
var event; // The custom event that will be created
if(document.createEvent){
event = document.createEvent("HTMLEvents");
event.initEvent("dataavailable", true, true);
event.eventName = "dataavailable";
element.dispatchEvent(event);
} else {
event = document.createEventObject();
event.eventName = "dataavailable";
event.eventType = "dataavailable";
element.fireEvent("on" + event.eventType, event);
}
回答by Dorian
A working example:
一个工作示例:
// Add an event listener
document.addEventListener("name-of-event", function(e) {
console.log(e.detail); // Prints "Example of an event"
});
// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });
// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
For older browsers polyfilland more complex examples, see MDN docs.
对于较旧的浏览器polyfill和更复杂的示例,请参阅MDN 文档。
See support tables for EventTarget.dispatchEventand CustomEvent.
回答by e18r
If you don't want to use jQuery and aren't especially concerned about backwards compatibility, just use:
如果您不想使用 jQuery 并且不是特别关心向后兼容性,只需使用:
let element = document.getElementById(id);
element.dispatchEvent(new Event("change")); // or whatever the event type might be
See the documentation hereand here.
EDIT:Depending on your setup you might want to add bubbles: true:
编辑:根据您的设置,您可能想要添加bubbles: true:
let element = document.getElementById(id);
element.dispatchEvent(new Event('change', { 'bubbles': true }));
回答by Hilder Vitor Lima Pereira
if you use jQuery, you can simple do
如果你使用jQuery,你可以简单地做
$('#yourElement').trigger('customEventName', [arg0, arg1, ..., argN]);
and handle it with
并处理它
$('#yourElement').on('customEventName',
function (objectEvent, [arg0, arg1, ..., argN]){
alert ("customEventName");
});
where "[arg0, arg1, ..., argN]" means that these args are optional.
其中“[arg0, arg1, ..., argN]”表示这些参数是可选的。
回答by Mr. Polywhirl
If you are supporting IE9+ the you can use the following. The same concept is incorporated in You Might Not Need jQuery.
如果您支持 IE9+,则可以使用以下内容。你可能不需要 jQuery 中也包含了相同的概念。
function addEventListener(el, eventName, handler) {
if (el.addEventListener) {
el.addEventListener(eventName, handler);
} else {
el.attachEvent('on' + eventName, function() {
handler.call(el);
});
}
}
function triggerEvent(el, eventName, options) {
var event;
if (window.CustomEvent) {
event = new CustomEvent(eventName, options);
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent(eventName, true, true, options);
}
el.dispatchEvent(event);
}
// Add an event listener.
addEventListener(document, 'customChangeEvent', function(e) {
document.body.innerHTML = e.detail;
});
// Trigger the event.
triggerEvent(document, 'customChangeEvent', {
detail: 'Display on trigger...'
});
If you are already using jQuery, here is the jQuery version of the code above.
如果您已经在使用 jQuery,这里是上面代码的 jQuery 版本。
$(function() {
// Add an event listener.
$(document).on('customChangeEvent', function(e, opts) {
$('body').html(opts.detail);
});
// Trigger the event.
$(document).trigger('customChangeEvent', {
detail: 'Display on trigger...'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
回答by S.Mishra
I searched for firing click, mousedown and mouseup event on mouseover using JavaScript. I found an answer provided by Juan Mendes. For the answer click here.
我使用 JavaScript 在鼠标悬停时搜索触发点击、鼠标按下和鼠标按下事件。我找到了Juan Mendes提供的答案。答案请点击这里。
Click hereis the live demo and below is the code:
点击这里是现场演示,下面是代码:
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9) {
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
var bubbles = eventName == "change" ? false : true;
event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
回答by Kirby L. Wallace
Just to suggest an alternative that does not involve the need to manually invoke a listener event:
只是建议一种不需要手动调用侦听器事件的替代方法:
Whatever your event listener does, move it into a function and call that function from the event listener.
无论您的事件侦听器做什么,都将其移动到一个函数中并从事件侦听器中调用该函数。
Then, you can also call that function anywhere else that you need to accomplish the same thing that the event does when it fires.
然后,您还可以在需要完成与事件触发时相同的事情的任何其他地方调用该函数。
I find this less "code intensive" and easier to read.
我发现这不那么“代码密集”并且更容易阅读。
回答by Aleksander Lech
I just used the following (seems to be much simpler):
我只是使用了以下内容(似乎要简单得多):
element.blur();
element.focus();
In this case the event is triggered only if value was really changed just as you would trigger it by normal focus locus lost performed by user.
在这种情况下,只有当值真的改变时才会触发事件,就像用户执行的正常焦点轨迹丢失一样触发它。
回答by Yarin
Modified @Dorian's answerto work with IE:
修改了@Dorian 的回答以使用 IE:
document.addEventListener("my_event", function(e) {
console.log(e.detail);
});
var detail = 'Event fired';
try {
// For modern browsers except IE:
var event = new CustomEvent('my_event', {detail:detail});
} catch(err) {
// If IE 11 (or 10 or 9...?) do it this way:
// Create the event.
var event = document.createEvent('Event');
// Define that the event name is 'build'.
event.initEvent('my_event', true, true);
event.detail = detail;
}
// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
FIDDLE:https://jsfiddle.net/z6zom9d0/1/
小提琴:https ://jsfiddle.net/z6zom9d0/1/
回答by Ming
The accepted answer didn't work for me, none of the createEvent ones did.
接受的答案对我不起作用,createEvent 的都没有。
What worked for me in the end was:
最后对我有用的是:
targetElement.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window,
}));
Here's a snippet:
这是一个片段:
const clickBtn = document.querySelector('.clickme');
const viaBtn = document.querySelector('.viame');
viaBtn.addEventListener('click', function(event) {
clickBtn.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window,
}));
});
clickBtn.addEventListener('click', function(event) {
console.warn(`I was accessed via the other button! A ${event.type} occurred!`);
});
<button class="clickme">Click me</button>
<button class="viame">Via me</button>
From reading: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
从阅读:https: //developer.mozilla.org/en-US/docs/Web/API/MouseEvent

