'undefined'不是在Safari中评估el.click()的函数 [英] 'undefined' is not a function evaluating el.click() in Safari

查看:45
本文介绍了'undefined'不是在Safari中评估el.click()的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按Enter按钮运行js函数.一切都可以在IE,Chrome和Opera中正常运行,但是在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.

我需要一个纯JavaScript 解决方案,不是jQuery .

I need a pure Javascript solution, not jQuery.

这是功能:

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

这是 HTML :

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

我收到此错误:

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

我在做什么错了?

编辑:我已修复Mozilla Firefox错误.

I've fixed the Mozilla Firefox error.

推荐答案

如果您查看

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.

在现代浏览器中触发事件的正确方法是 DOM级别3个活动:

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

以下是可在Chrome,Safari,Firefox和IE9中使用的jsfiddle: http://jsfiddle.net/y5yW9/6/

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

这篇关于'undefined'不是在Safari中评估el.click()的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆