如何在JavaScript中触发事件?

时间:2010-03-22 08:41:36

标签: javascript events javascript-events triggers addeventlistener

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

我该怎么做?

18 个答案:

答案 0 :(得分:425)

您可以在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);
} else {
  event = document.createEventObject();
  event.eventType = "dataavailable";
}

event.eventName = "dataavailable";

if (document.createEvent) {
  element.dispatchEvent(event);
} else {
  element.fireEvent("on" + event.eventType, event);
}

答案 1 :(得分:290)

一个工作示例:

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

答案 2 :(得分:38)

如果你使用jQuery,你可以简单地做

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

并用

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

其中" [arg0,arg1,...,argN]"意味着这些args是可选的。

答案 3 :(得分:32)

如果您不想使用jQuery并且不特别关注向后兼容性,请使用:

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

请参阅文档herehere

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

let element = document.getElementById(id);
element.dispatchEvent(new Event('change', { 'bubbles': true });

答案 4 :(得分:24)

如果您支持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...'
});




如果您已经在使用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>
&#13;
&#13;
&#13;

答案 5 :(得分:13)

我使用JavaScript在mouseover上搜索了click 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);
    }
};

答案 6 :(得分:7)

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

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

然后,您还可以在其他任何地方调用该函数,以完成事件发生时所执行的操作。

我发现这个代码密集度较低&#34;并且更容易阅读。

答案 7 :(得分:5)

我刚刚使用了以下内容(似乎更简单):

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

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

答案 8 :(得分:5)

修改了@ 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/

还请参见:
https://caniuse.com/#feat=customevent

答案 9 :(得分:3)

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

答案 10 :(得分:2)

接受的答案对我不起作用,所有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

答案 11 :(得分:1)

您可以使用我一起编译的此功能。

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

希望这会有所帮助!

答案 12 :(得分:1)

您可以使用以下代码通过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);
        }
    };
}

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>

答案 13 :(得分:0)

var btn = document.getElementById('btn-test');
var event = new Event(null);

event.initEvent('beforeinstallprompt', true, true);
btn.addEventListener('beforeinstallprompt', null, false);
btn.dispatchEvent(event);

这将在安装提示&#39;

之前触发事件&#39;

答案 14 :(得分:0)

最有效的方法是直接调用已在addEventListener注册的相同功能。

您还可以使用CustomEvent和co。

触发假冒事件

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

答案 15 :(得分:-1)

使用jquery事件调用。 在下面的行中写下要触发任何元素的onChange。

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

element_id 是您要触发其onChange的元素的ID。

避免使用

 element.fireEvent("onchange");

因为它的支持很少。请参阅此文档以查看其support

答案 16 :(得分:-2)

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 
}

答案 17 :(得分:-11)

你想要的是这样的:

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

使用jQuery,它将是这样的:

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