Answers:
您可以在IE 8或更低版本上使用fireEvent,在大多数其他浏览器上使用W3C的dispatchEvent。要创建您要触发的事件,可以使用或取决于浏览器。createEvent
createEventObject
这是一段不言自明的代码(来自原型),它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);
}
eventName
在这里包含什么?
一个工作示例:
// 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);
detail
是的属性Event
,因此,将要在另一端访问的任何数据分配给,并通过进行访问event.detail
。+1
如果您不想使用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 }));
CustomEvent
,您应该使用和相应的polyfill。
如果您使用jQuery,则可以简单地执行
$('#yourElement').trigger('customEventName', [arg0, arg1, ..., argN]);
并用
$('#yourElement').on('customEventName',
function (objectEvent, [arg0, arg1, ..., argN]){
alert ("customEventName");
});
其中的[[arg0,arg1,...,argN]]表示这些args是可选的。
如果您支持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>
window.CustomEvent
存在),但不能作为构造函数调用:caniuse.com/#search=CustomEvent ;)
我使用JavaScript搜索了在鼠标悬停时触发click,mousedown和mouseup事件。我找到了Juan Mendes提供的答案。要获得答案,请单击此处。
单击此处是现场演示,下面是代码:
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();
在这种情况下,仅当值确实发生更改时才触发该事件,就像您由用户执行的正常焦点轨迹丢失触发该事件一样。
element.click()
。
修改@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);
内容: https ://jsfiddle.net/z6zom9d0/1/
接受的答案对我不起作用,所有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>
通过阅读:https : //developer.mozilla.org/en-US/docs/Web/API/MouseEvent
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");
您可以使用我一起编译的此功能。
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);
});
希望这可以帮助!
您可以使用以下代码通过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);
}
};
}
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事件调用。将以下行写在要触发任何元素的onChange的位置。
$("#element_id").change();
element_id是要触发其onChange的元素的ID。
避免使用
element.fireEvent("onchange");
因为它的支持很少。请参阅本文档以获取支持。
的HTML
<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
}
您想要的是这样的:
document.getElementByClassName("example").click();
使用jQuery,将是这样的:
$(".example").trigger("click");
document.getElementByClassName
不存在。2. document.getElementsByClassName
存在但返回列表。3.这仅适用于少数几个本地事件。4.最后一个示例触发一个jQuery事件,其中不存在任何底层本机事件。