FireFox下为元素附加事件并传递参数-addEventListener attachEvent - Pass parameters to event-function...

本文介绍了如何在浏览器中为HTML元素绑定事件,并通过这些事件访问元素的属性,如'id'和'name'等。同时展示了如何设置自定义属性并在事件触发时读取这些属性。
But you can get information of the object where the event occured. E.g. you can do stuff dependent on the "id" of an object, or you can set any additional flags within the object and do stuff dependent on these flags.

Here we have the code for attaching the events:
if(window.addEventListener){ // Mozilla, Netscape, Firefox
object.addEventListener('mouseover', testevent, false);
object.addEventListener('click', testevent, false);
object.myflag = "test";
object.mydata = "123";
} else { // IE
object.attachEvent('onmouseover', testevent);
object.attachEvent('onclick', testevent);
object.myflag = "test";
object.mydata = "123";
}

The function "testevent" contains all code to access the "id", "name" etc. and all own flags:
function testevent(evt){
var e_out;
var ie_var = "srcElement";
var moz_var = "target";
var prop_var = "myflag";
// "target" for Mozilla, Netscape, Firefox et al. ; "srcElement" for IE
evt[moz_var] ? e_out = evt[moz_var][prop_var] : e_out = evt[ie_var][prop_var];
alert(e_out);
prop_var = "mydata";
evt[moz_var] ? e_out = evt[moz_var][prop_var] : e_out = evt[ie_var][prop_var];
alert(e_out);
}


Conclusion: If you set appropriate flags when attaching an event to an object, you have the possiblity to do actions dependent on these flag when the actual event occurs.
Therefore it is not necessary to pass parameters directly when attaching the event, since those parameters either do not change anyway, or if the parameters are dynamically created, those dynamic parameters can be read out in the function "testevent".

转载于:https://www.cnblogs.com/goody9807/archive/2008/04/21/1163992.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值