如何在JavaScript中触发事件?

我已使用将事件附加到文本框addEventListener它工作正常。当我想通过另一个函数以编程方式触发事件时,出现了我的问题。

我该怎么做?

小小Jim2020/03/12 16:42:39

Use jquery event call. Write the below line where you want to trigger onChange of any element.

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

element_id is the ID of the element whose onChange you want to trigger.

Avoid the use of

 element.fireEvent("onchange");

Because it has very less support. Refer this document for its support.

老丝Near2020/03/12 16:42:39

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.

古一阳光2020/03/12 16:42:39

What you want is something like this:

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

Using jQuery, it would be something like this:

$(".example").trigger("click");
宝儿卡卡西理查德2020/03/12 16:42:38
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");
斯丁卡卡西2020/03/12 16:42:38

我只使用了以下内容(似乎要简单得多):

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

在这种情况下,仅当值确实发生更改时才触发该事件,就像您由用户执行的正常焦点轨迹丢失触发该事件一样。

番长神乐小小2020/03/12 16:42:38

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

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

然后,您还可以在需要完成事件触发时执行的相同操作的任何其他位置调用该函数。

我发现这种方式“代码密集型”较少,而且更易于阅读。

老丝镜风2020/03/12 16:42:38

一个工作示例:

// 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 docs

见支持表的EventTarget.dispatchEventCustomEvent

Stafan樱2020/03/12 16:42:38

您可以IE 8或更低版本使用fireEvent大多数其他浏览器上使用W3C的dispatchEvent要创建您要触发的事件,可以使用取决于浏览器。createEventcreateEventObject

这是一段不言自明的代码(来自原型),它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);
}