Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

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

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 pure Javascript solution, not jQuery.

This is the function:

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) {
        document.getElementById('enterSearch').click();
    }
}

This is the HTML:

<input type="text" id="searchKey" onkeypress="pressSearch(event)">
<div id="enterSearch">Search</div> // This is the "button"

I get this error:

// Safari
TypeError: 'undefined' is not a function 
    (evaluating 'getElementById('enterSearch').click()')

What am I doing wrong?

EDIT: I've fixed the Mozilla Firefox error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you take a look at the HTML DOM Level 2 Specification, the click() function is only defined for HTMLInputElement, so while certainly not very user-friendly Safari doesn't need to implement that.

The correct way to trigger an event for modern browsers is in DOM Level 3 Events:

// First create an event
var click_ev = document.createEvent("MouseEvents");
// initialize the event
click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
// trigger the event
document.getElementById("someElement").dispatchEvent(click_ev);

Here's jsfiddle that works in Chrome, Safari, Firefox and IE9: http://jsfiddle.net/y5yW9/6/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...