Mozilla中未调用Div onclick事件 [英] Div onclick event not called in Mozilla

查看:59
本文介绍了Mozilla中未调用Div onclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有这个

<div class="someClass">
    <div id="22" class="otherClass" onclick="goToEdit();">Title</div>
    <div class="parent">Other title</div>
</div>

并且:

function goToEdit()
{
    tree.selectItem($(event.target).attr('id'));
    btnMyButton_onclick();
}

在Chrome中,一切正常,但在Mozilla中,它对click事件没有反应.为什么?

In Chrome everything works fine, but in Mozilla it doesn't react to the click event. Why?

推荐答案

我收到未定义事件的错误消息

I get error that event is not defined

Do!我们都应该意识到.

问题是event在大多数浏览器中都不是全局的,尽管它在IE上,并且Chrome通过使其具有全局性以及应做的事情(将其传递到事件处理函数).

The thing is that event is not a global on most browsers, though it is on IE and Chrome throws a bone to sites designed for IE by making it global as well as doing what it should do (passing it into the event handler function).

到目前为止,您最好的选择是根本不使用onclick="code"(请参见下文),但是您也可以这样做:

Your best bet by far is to not use onclick="code" at all (see below), but you can also do this:

<div id="22" class="otherClass" onclick="goToEdit(event);">Title</div>

...应该可以跨浏览器使用.之所以起作用,是因为event对象是在特殊的上下文中定义的,在该上下文中调用onclick处理程序(在以标准方式执行此操作的浏览器上),或者它是全局的(在IE上),因此无论在哪种方式下都将其定义为这一点(但不一定是全局的,稍后在您的goToEdit函数中,这就是我们将其作为参数传递的原因.)

...which should work cross-browser. It works because the event object is defined in the special context in which onclick handlers are called (on browsers that do this in a standard way), or it's a global (on IE), and so either way it's defined at that point (but not necessarily, as a global, later in your goToEdit function — which is why we pass it in as an argument).

但是,我不会那样做.相反,我要使id值对CSS有效,方法是使它以字母开头,并使用jQuery来连接处理程序:

But again, I wouldn't do that. Instead, I'd make the id value valid for CSS by having it start with a letter, and use jQuery to hook up the handler:

HTML:

<div id="d22" class="otherClass">Title</div>

JavaScript:

JavaScript:

$("#d22").click(goToEdit);
function goToEdit(event) {
    tree.selectItem(event.target.id.substring(1));
    btnMyButton_onclick();
}

注意:

  • 我将d的值从id的开头剥离掉,然后再传递给它.我认为这是22原因.
  • 没有理由做$(event.target).attr('id'),只需直接使用event.target.id.
  • 如果div可能包含其他元素(span s,em s,p s等),请注意,event.target可能不是div,则可能是div的后代元素.但是,this始终是div,(jQuery看到了),所以:

  • I striped the d off the beginning of the id value before passing it on. I assume it was 22 for a reason.
  • There's no reason to do $(event.target).attr('id'), just use event.target.id directly.
  • If the div may contain other elements (spans, ems, ps, etc.), note that event.target may not be the div, it may be a descendant element of the div. this will always be the div, though (jQuery sees to that), so:

$("#d22").click(goToEdit);
function goToEdit(event) {
    tree.selectItem(this.id.substring(1));
    btnMyButton_onclick();
}

这篇关于Mozilla中未调用Div onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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