我已使用将事件附加到文本框addEventListener
。它工作正常。当我想通过另一个函数以编程方式触发事件时,出现了我的问题。
我该怎么做?
我已使用将事件附加到文本框addEventListener
。它工作正常。当我想通过另一个函数以编程方式触发事件时,出现了我的问题。
我该怎么做?
The most efficient way is to call the very same function that has been registered with addEventListener
directly.
You can also trigger a fake event with CustomEvent
and co.
Finally some elements such as <input type="file">
support a .click()
method.
What you want is something like this:
document.getElementByClassName("example").click();
Using jQuery, it would be something like this:
$(".example").trigger("click");
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");
我只使用了以下内容(似乎要简单得多):
element.blur();
element.focus();
在这种情况下,仅当值确实发生更改时才触发该事件,就像您由用户执行的正常焦点轨迹丢失触发该事件一样。
只是建议一个不需要手动调用侦听器事件的替代方法:
无论事件侦听器做什么,都将其移到函数中并从事件侦听器中调用该函数。
然后,您还可以在需要完成事件触发时执行的相同操作的任何其他位置调用该函数。
我发现这种方式“代码密集型”较少,而且更易于阅读。
一个工作示例:
// 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);
您可以在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);
}
Use jquery event call. Write the below line where you want to trigger onChange of any element.
element_id is the ID of the element whose onChange you want to trigger.
Avoid the use of
Because it has very less support. Refer this document for its support.