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

后端 未结 5 507
眼角桃花
眼角桃花 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 16:11

    A div element has no click event handler defined per default. So, first you need to apply a click event for the enterSearch div, e.g.

    Search
    . Otherwise the button itself won't be clickable.

    To execute an event programmatically, use this construct:

    function pressSearch(e) {
        if (typeof e == 'undefined' && window.event) {
            e = window.event;
        }
    
        var charCode = (e.which) ? e.which : ((e.charCode) ? e.charCode : ((e.keyCode) ? e.keyCode : 0));
        if (charCode == 13) {
            var a = document.getElementById('enterSearch');
    
            if (typeof a.onclick == "function") {
                a.onclick.apply(a); // binds the scope of onclick to a
            }
        }
    }
    

    I could not validate this for IE, but it works with Safari.

提交回复
热议问题