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

我该怎么做呢?


当前回答

如果你不想使用jQuery,也不特别关心向后兼容性,可以使用:

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

请在这里和这里查看文档。

编辑:根据你的设置,你可能想要添加气泡:true:

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

其他回答

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

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

然后用

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

[arg0, arg1,…], argN]表示这些参数是可选的。

我使用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);
    }
};

你想要的是这样的:

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

使用jQuery,它是这样的:

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

接受的答案不适合我,createEvent的都不行。

最后对我有用的是:

targetElement.dispatchEvent(
    new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window,
}));

Here’s a snippet: 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

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

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

希望这能有所帮助!