我正在尝试向事件原型添加一个方法。为了呼叫/设置preventDefault()
或者,用 IE 来说returnValue = false
以及-如果需要的话-stopPropagation()
/ cancelBubble = true;
。我认为下面的代码就足够了。
Event = Event || window.Event;
//^^ makes the fiddle work on IE8 ^^
if(!(Event.prototype.stopEvent))
{
Event.prototype.stopEvent = function(propagate)
{
"use strict";
propagate = (propagate ? true : false);
if (this.preventDefault)
{
this.preventDefault();
if (propagate === false)
{
this.stopPropagation();
}
}
else
{
this.returnValue = false;
this.cancelBubble = !propagate;
}
return this;
};
}
这似乎有效,正如你可以在这里看到的 http://jsfiddle.net/v4sTx/4/。这个小提琴显示OK
在 IE8、Firefox 和 Chrome 中。不过,当我将其添加到我的脚本中时,IE8 在第一行中断,说“事件未定义”。离开了"use strict";
完全没有区别。
无奈之下,我也尝试了这个:
if (typeof Event === 'undefined')
{
var Event = window.Event || window.event;//FFS IE :-(
}
但无济于事:Error: 'Event.prototype' is null or not an object
,所以我又多了 1 行。问题是,整个原型方法是从我的脚本中复制粘贴的,但我在这里忽略了什么?有什么想法/建议吗?
Thanks
PS:我喜欢纯 JavaScript,所以请不要建议使用 jQuery、prototypejs、dojo...作为解决方案。我刚刚摆脱了 jQuery。 (我喜欢 jQuery,但在这种情况下不需要它)
Update
恐怕事情已经变得更糟了。我发现这个MSDN参考 http://msdn.microsoft.com/en-us/library/dd229916(v=vs.85).aspx。整个页面涉及 DOM 元素原型。可以公平地说它们在 IE8 中可用(在某种程度上)。在这个页面上,这段代码引起了我的注意:
Event.prototype.stopPropagation = function ()
{
this.cancelBubble = true;
};
Event.prototype.preventDefault = function ()
{
this.returnValue = false;
};
它可以在下页的 3/4 标题为的部分中找到"Powerful Scenarios"
。在我看来,这与我想做的事情完全相同,但更重要的是:如果我通过 jsfiddle 尝试此代码,它甚至不起作用,而我的 jsfiddle (带有我的代码)在 IE8 上可以工作。这只是代码片段的最后几行,但据我所知,这几行代码应该可以正常工作。我已将它们更改如下:
Event.prototype.stopPropagation = function ()
{
if (this.stopPropagation)
{
return this.stopPropagation();
}
this.cancelBubble = true;
};
Event.prototype.preventDefault = function ()
{
if (this.preventDefault)
{
return this.preventDefault();
}
this.returnValue = false;
};