'undefined' is not a function evaluating el.click() in Safari

后端 未结 5 531
眼角桃花
眼角桃花 2020-12-10 15:46

I would like to run a js function on pressing Enter button. Everything works great in IE, Chrome and Opera, but I get an error (explained below) in Safari.

I need a

5条回答
  •  遥遥无期
    2020-12-10 15:53

    I came across this same issue while working on a similar problem. What I came up with is the following for triggering click events in safari(as well as other browsers, of course):

    var t = document.getElementById('someidhere');
    if (document.dispatchEvent) {
        var e = new MouseEvent('click', {
            view: window,    // Window associated with the event
            bubbles: true,
            cancelable: true
        });
        t.dispatchEvent(e);
    } else if (document.fireEvent) {
        t.fireEvent('onclick');
    } else if (t.click) {
        t.click();
    }
    

    According to @Dennis, your code already works for Firefox, however this code should work in Firefox anyway as of version 79.0(the version it was tested in).

    Note that initEvent() has been deprecated. The new method of creating the event through the Event constructor doesn't work in Internet Explorer, however.

提交回复
热议问题