如何在JavaScript中触发事件?

查看原始版本

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

我该怎么做?

所有回答
  • Maxwell Lee #1

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

    下面是一段自解释的代码(来自prototype),它在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);
    }
    
  • Camille Lee #2

    一个有效的例子:

    // 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的支持表

  • Kay Lee #3

    如果您不想使用jQuery,也不特别关心向后兼容性,只需使用:

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

    请参阅文档herehere

    EDIT:根据您的设置,您可能需要添加bubbles: true

    let element = document.getElementById(id);
    element.dispatchEvent(new Event('change', { 'bubbles': true }));
    
  • Barnett Lee #4
    如果使用jQuery,您可以简单地

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

    处理它

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

    其中“[arg0,arg1,…,argN]”表示这些参数是可选的

  • Natividad Lee #5

    如果您支持IE9+,则可以使用以下命令。同样的概念也包含在You Might Not Need 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...'
    });
  • Ronald Lee #6

    我使用JavaScript搜索mouseover上的firing click、mousedown和mouseup事件。我找到了Juan Mendes提供的答案。有关答案,请单击here

    点击here是现场演示,下面是代码:

    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);
        }
    };
    
  • Ed Lee #7

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

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

    然后,您还可以在任何其他地方调用该函数,以完成事件激发时所做的相同操作

    我发现这个“代码密集型”更少,更容易阅读

  • Nathaniel Lee #8

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

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

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

  • Philip Lee #9

    修改@Dorian的answer以与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);
    

    FIDDLE:https://jsfiddle.net/z6zom9d0/1/

    SEE ALSO:
    https://caniuse.com/#feat=customevent

  • Mandel Lee #10
    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");
    
  • David Lee #11

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

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

    希望这有帮助!

  • Benjamin Lee #12

    可以使用以下代码使用元素方法触发事件:

    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>
  • Dolores Lee #13

    最有效的方法是直接调用注册到addEventListener的同一个函数

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

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

  • Upton Lee #14
    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'

  • Quincy Lee #15

    使用jquery事件调用。 在要触发任何元素更改的地方编写下面的一行

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

    element\u id是要触发其onChange的元素的id

    避免使用

     element.fireEvent("onchange");
    

    因为它的支持率很低。请参阅本文件的support

  • Fay Lee #16
    以HTML/p为准
    <a href="demoLink" id="myLink"> myLink </a>
    <button onclick="fireLink(event)"> Call My Link </button>
    
    在越狱前。。。
    // 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 
    }
    
  • Burgess Lee #17

    你想要的是这样的东西:

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

    使用jQuery,可能是这样的:

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