我已经使用addEventListener将事件附加到文本框。它工作得很好。当我想从另一个函数以编程方式触发事件时,问题就出现了。
我该怎么做呢?
我已经使用addEventListener将事件附加到文本框。它工作得很好。当我想从另一个函数以编程方式触发事件时,问题就出现了。
我该怎么做呢?
当前回答
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");
其他回答
注意:initEvent方法现在已弃用。其他回答功能最新的和建议的做法。
你可以在ie8或更低版本上使用fireEvent,在大多数其他浏览器上使用W3C的dispatchEvent。要创建想要触发的事件,可以根据浏览器使用createEvent或createEventObject。
下面是一段不言自明的代码(来自原型),它可以触发元素上可用的事件数据:
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);
}
我使用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);
}
};
值得注意的是,我们可以创建任何类型的预定义事件,并在任何地方收听。
我们并不局限于经典的内置事件。
在这个基本示例中,自定义事件interfacebuiltsuccessuserdefinedevent每3秒在self.document上分派一次
self.document。addEventListener('interfacebuiltsuccessuserdefinedevent', () => console.log("WOW"), false) setInterval(() =>{//测试 self.document。dispatchEvent(新事件(interfacebuiltsuccessuserdefinedevent)) }, 3000) //测试
有趣的事实:元素可以侦听尚未创建的事件。
修改@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/
参见: https://caniuse.com/#feat=customevent
如果你使用jQuery,你可以简单做到
$('#yourElement').trigger('customEventName', [arg0, arg1, ..., argN]);
然后用
$('#yourElement').on('customEventName',
function (objectEvent, [arg0, arg1, ..., argN]){
alert ("customEventName");
});
[arg0, arg1,…], argN]表示这些参数是可选的。