直到今天我才弄清楚事件传播是如何运作的,并且在我现有的代码库中进行了大量的测试,但是arghhhhhhhh该死的javascript ......对你来说似乎没什么好看的:X
这是我的问题,我在锚上定义了一组事件:
theLink.setAttribute('onMouseOver','doSomething(this)'); **// works**
theLink.addEventListener("mouseout", function(event){doSomethingElse(event)}, false); **// does not work**
theLink.onmouseout = function(event){doSomethingElse(event)}; **// does not work**
只有我在第一个例子中定义事件时,它似乎也在第二个或第三个定义中工作。但我无法使用该定义,因为我必须传递事件对象。
任何提示?我正在使用firefox。
答案 0 :(得分:3)
所有这三个都使用以下代码(在Firefox中)为我工作:
HTML:
<a id="link1">Link 1</a>
<a id="link2">Link 2</a>
<a id="link3">Link 3</a>
JS:
var link1 = document.getElementById("link1");
var link2 = document.getElementById("link2");
var link3 = document.getElementById("link3");
window.doSomething = function(event) {
console.log(event);
}
link1.setAttribute('onMouseOver', 'doSomething(this)');
link2.addEventListener("mouseout", function(event) {
doSomething(event)
}, false);
link3.onmouseout = function(event) {
doSomething(event)
};
这是一个有效的jsfiddle:http://jsfiddle.net/magicaj/qk6wU/
您也可以考虑使用像jQuery这样的库来处理与某些版本的IE不支持的addEventListener
方法的跨浏览器不兼容,JS看起来像这样:
$("#link1").mouseover(doSomething);
$("#link2").mouseover(doSomething);
$("#link3").mouseover(doSomething);
答案 1 :(得分:2)
包含跨浏览器的答案
function doSomething( event ) {
if( console && console.log ) {
console.log( this );
console.log( event );
}
else {
alert( this === window ? 'WINDOW' : this.tagName );
alert( event );
}
}
var link1 = document.getElementById("link1");
var link2 = document.getElementById("link2");
var link3 = document.getElementById("link3");
// `this` within your handler will be `window` and not the link
link1.setAttribute( 'onMouseOver', 'doSomething( event )' );
// to attach event listeners you have to do a bit more work
// ( best to make a function rather than doing this each time
if( document.addEventListener ) {
// compliant browsers
link2.addEventListener('mouseover', doSomething, false);
} else {
// internet explorer
link2.attachEvent( 'onmouseover', function() {
// grab the event object from the window
var e = window.event;
// normalise it a bit i.e. make it a bit more like a compliant browsers event object
e.target = e.srcElement;
e.preventDefault = function(){ e.returnValue = false };
e.stopPropagation = function(){ e.cancelBubble = true };
// and forward to your handler making sure that `this` is properly set
doSomething.call( this, e );
});
}
link3.onclick = doSomething;
注意强>
避免将处理程序包装在不必要的匿名函数中,这会浪费你的力量而你会丢失处理程序中的this
所以而不是
link3.onclick = function( event ) { doSomething( event ) };
直接分配处理程序
link3.onclick = doSomething;