使用prototypejs 1.7_rc2在IE8中进行奇怪的单击事件行为

时间:2010-07-18 16:17:19

标签: javascript internet-explorer event-handling prototypejs

我有一些javascript点击处理程序在IE8中没有做我想要的。我想要做的是在第一次点击时调用处理程序,然后在所有后续点击上调用另一个处理程序。我这样做的方法是将原始处理程序放在onclick属性中,然后使用该处理程序擦除onclick属性并使用Event#observe设置在后续点击时调用的处理程序但由于某种原因IE8拒绝合作。而不是以下程序流程

click->call originalHandler->erase originalHandler->set newHandler 

我得到了意想不到的程序流程

click->call originalHandler->erase originalHandler->set newHandler->call newHandler 

我无法弄清楚为什么单击事件会触发两个处理程序。以下是违规代码的片段,pastie linklink到一个页面,该页面通过ie8一直在我的笔记本电脑上重现错误。

//weird behavior in the latest prototype version with ie8
function originalHandler(event) {
  Event.stop(event); //this doesn't help either, the event still triggers newHandler
  var button = $('button');
  alert("first click");
  button.writeAttribute({onclick:null});
  function newHandler(event) {
    //this should only show up on the second click
    //but it shows up on the first click as well
    alert('second click');
  }
  button.observe('click',newHandler);
}

因此,要获得所需的行为,我必须添加一个额外的间接层,这看起来很奇怪。所以下面的代码修复了IE8的问题但是破坏了firefox和chrome行为,因为现在“第二次点击”直到第三次点击才会显示。这是适用于IE8的版本的pastie和适用于IE8的页面的link,但需要额外点击chrome和firefox。

function originalHandler(event) {
  Event.stop(event);
  var button = $('button');
  alert("first click");
  button.writeAttribute({onclick:null});
  var newHandler = function(ev) {
    button.stopObserving();
    button.observe('click',function() {alert("second click");});
  }
  button.observe('click',newHandler);
}

有关如何修复此错误并在所有浏览器中获得一致行为的任何想法?

1 个答案:

答案 0 :(得分:0)

我还问过原型邮件列表,我得到的答案是,基本上发生的是IE8调用DOM0处理程序,然后调用DOM2处理程序,这就是我用Element#observe设置的方法及其解决方法是设置一个延迟,以便DOM2处理程序不会设置,直到第一个事件一直冒泡,没有任何DOM2处理程序。哦,我讨厌跨浏览器的兼容性。