我正在尝试通过javascript在页面上添加事件处理程序。我尝试的内容如下,
var span=document.getElementById("WD67");
span.setAttribute("onchange","alert('hello');");
但是虽然添加了事件处理程序属性,但在IE中查看页面时它不会触发,但在Firefox中它可以正常工作。我如何让IE识别它?
答案 0 :(得分:3)
var span = document.getElementById("WD67");
span.onchange = function(){ alert('hello'); };
答案 1 :(得分:1)
不要使用属性。添加事件处理程序的最佳方法是使用addEventListener
(所有现代浏览器)或attachEvent
(IE <9)。此外,使用处理函数引用(在函数中包裹alert('hello')
)。
用于向元素添加处理程序的crossbrowser函数:
function addHandler(obj,htype,fn){
if (obj.addEventListener){
obj.addEventListener(htype, fn);
} else {
obj.attachEvent('on'+htype,fn);
}
}
// usage
var mySpan=document.getElementById("WD67");
addHandler(mySpan,'change',function(){alert('hello')});
另请参阅:this jsfiddle