如何在JavaScript中触发事件?

我使用addEventListener将一个事件附加到一个文本框。它工作得很好。当我想从另一个函数以编程方式触发事件时,问题就出现了。

我该怎么做呢?

947683 次浏览

注意:initEvent方法现在已弃用。其他回答功能最新的和建议的做法。


你可以在IE 8或更低的浏览器上使用fireEvent,在大多数上使用W3C的dispatchEvent。要创建想要触发的事件,可以根据浏览器使用createEventcreateEventObject

下面是一段自解释的代码(来自原型),它在element上触发dataavailable事件:

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);
}

一个工作的例子:

// 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);

对于旧的浏览器polyfill和更复杂的示例,请参阅MDN文档

请参阅EventTarget.dispatchEventCustomEvent的支持表。

如果你使用jQuery,你可以简单做到

$('#yourElement').trigger('customEventName', [arg0, arg1, ..., argN]);

然后用

$('#yourElement').on('customEventName',
function (objectEvent, [arg0, arg1, ..., argN]){
alert ("customEventName");
});

[arg0, arg1,…], argN]表示这些参数是可选的。

你想要的是这样的:

document.getElementByClassName("example").click();

使用jQuery,它是这样的:

$(".example").trigger("click");

我使用JavaScript搜索了鼠标悬停时的触发点击,鼠标下拉和鼠标上拉事件。我找到了胡安·门德斯提供的答案。点击在这里查看答案。

点击在这里是现场演示,下面是代码:

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);
}
};

我只是使用了以下方法(似乎更简单):

element.blur();
element.focus();

在这种情况下,只有当值真的发生改变时才会触发事件,就像由用户执行的正常焦点轨迹丢失会触发它一样。

注意:initCustomEvent方法现在已弃用。其他回答功能最新的和建议的做法。


如果您支持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...'
});


如果您已经在使用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>

只是建议一个不需要手动调用监听器事件的替代方案:

无论您的事件侦听器做什么,都要将其移动到一个函数中,并从事件侦听器调用该函数。

然后,您还可以在需要完成与事件触发时相同的事情的其他任何地方调用该函数。

我发现这种方法不那么“代码密集”,也更容易阅读。

function fireMouseEvent(obj, evtName) {
if (obj.dispatchEvent) {
//var event = new Event(evtName);
var event = document.createEvent("MouseEvents");
event.initMouseEvent(evtName, true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
obj.dispatchEvent(event);
} else if (obj.fireEvent) {
event = document.createEventObject();
event.button = 1;
obj.fireEvent("on" + evtName, event);
obj.fireEvent(evtName);
} else {
obj[evtName]();
}
}


var obj = document.getElementById("......");
fireMouseEvent(obj, "click");

最有效的方法是直接调用已在addEventListener中注册的相同函数。

你也可以用CustomEvent和co触发一个假事件。

最后,一些元素(如<input type="file">)支持.click()方法。

使用jquery事件调用。

.

.

.

.

.
$("#element_id").change();

element_id是你想要触发其onChange的元素的ID。

避免使用

 element.fireEvent("onchange");

因为它的支撑力非常小。请参考该文档中的支持

修改@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);

# EYZ0 # EYZ1

< p > # EYZ0 < br > # EYZ0 < / p >
var btn = document.getElementById('btn-test');
var event = new Event(null);


event.initEvent('beforeinstallprompt', true, true);
btn.addEventListener('beforeinstallprompt', null, false);
btn.dispatchEvent(event);

这将立即触发事件“beforeinstallprompt”

如果你不想使用jQuery,也不特别关心向后兼容性,可以使用:

let element = document.getElementById(id);
element.dispatchEvent(new Event("change")); // or whatever the event type might be

请参阅文档在这里在这里

根据你的设置,你可能想添加bubbles: true:

let element = document.getElementById(id);
element.dispatchEvent(new Event('change', { 'bubbles': true }));

你可以使用我一起编译的这个函数。

if (!Element.prototype.trigger)
{
Element.prototype.trigger = function(event)
{
var ev;


try
{
if (this.dispatchEvent && CustomEvent)
{
ev = new CustomEvent(event, {detail : event + ' fired!'});
this.dispatchEvent(ev);
}
else
{
throw "CustomEvent Not supported";
}
}
catch(e)
{
if (document.createEvent)
{
ev = document.createEvent('HTMLEvents');
ev.initEvent(event, true, true);


this.dispatchEvent(event);
}
else
{
ev = document.createEventObject();
ev.eventType = event;
this.fireEvent('on'+event.eventType, event);
}
}
}
}

触发以下事件:

var dest = document.querySelector('#mapbox-directions-destination-input');
dest.trigger('focus');

观察事件:

dest.addEventListener('focus', function(e){
console.log(e);
});

希望这能有所帮助!

超文本标记语言

<a href="demoLink" id="myLink"> myLink </a>
<button onclick="fireLink(event)"> Call My Link </button>

JS

// click event listener of the link element --------------
document.getElementById('myLink').addEventListener("click", callLink);
function callLink(e) {
// code to fire
}


// function invoked by the button element ----------------
function fireLink(event) {
document.getElementById('myLink').click();      // script calls the "click" event of the link element
}

你可以使用下面的代码来使用Element方法触发事件:

if (!Element.prototype.triggerEvent) {
Element.prototype.triggerEvent = function (eventName) {
var event;


if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}


event.eventName = eventName;


if (document.createEvent) {
this.dispatchEvent(event);
} else {
this.fireEvent("on" + event.eventType, event);
}
};
}

if (!Element.prototype.triggerEvent) {
Element.prototype.triggerEvent = function (eventName) {
var event;


if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}


event.eventName = eventName;


if (document.createEvent) {
this.dispatchEvent(event);
} else {
this.fireEvent("on" + event.eventType, event);
}
};
}


var input = document.getElementById("my_input");
var button = document.getElementById("my_button");


input.addEventListener('change', function (e) {
alert('change event fired');
});
button.addEventListener('click', function (e) {
input.value = "Bye World";
input.triggerEvent("change");
});
<input id="my_input" type="input" value="Hellow World">
<button id="my_button">Change Input</button>

接受的答案不适合我,createEvent的都不行。

最后对我有用的是:

targetElement.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window,
}));

以下是片段:

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>

从阅读< p >: # EYZ0 < / p >