当我使用chrome来测试跨浏览器事件处理时,该函数不起作用。它表示“Uncaught TypeError:无法读取属性'addEventListener'为null”。据我所知,chrome支持“addEventListener”函数,但它无法识别函数。这是我的代码。
<!DOCTYPE html>
<html>
<head>
<title>event test</title>
</head>
<body>
<script type="text/javascript">
var EventUtil = {
addHandler : function(element, type, handler){
if (element.addEventListener){
element.addEventListener(type,handler,false);
}else if (element.attachEvent){
element.attachEvent("on" + type,handler);
}else{
element["on" + type] = handler;
}
},
removeHandler : function(element, type, handler){
if (element.removeEventListener){
element.removeEventListener(type,handler,false);
}else if (element.detachEvent){
element.detachEvent("on" + type,handler);
}else{
element["on" + type] = null;
}
}
};
var btn = document.getElementById('myBtn');
var handler1 = function(){
alert("Hello!");
};
EventUtil.addHandler(btn,"click",handler1);
</script>
<input type="button" name="mybutton" id="myBtn" value="myButton">
</body>
</html>
代码有什么问题?如何解决?
答案 0 :(得分:1)
在页面加载后执行您的javascript代码或将其放在html的末尾
<!DOCTYPE html>
<html>
<head>
<title>event test</title>
</head>
<body>
<input type="button" name="mybutton" id="myBtn" value="myButton">
</body>
<script type="text/javascript">
var EventUtil = {
addHandler : function(element, type, handler){
if (element.addEventListener){
element.addEventListener(type,handler,false);
}else if (element.attachEvent){
element.attachEvent("on" + type,handler);
}else{
element["on" + type] = handler;
}
},
removeHandler : function(element, type, handler){
if (element.removeEventListener){
element.removeEventListener(type,handler,false);
}else if (element.detachEvent){
element.detachEvent("on" + type,handler);
}else{
element["on" + type] = null;
}
}
};
var btn = document.getElementById('myBtn');
var handler1 = function(){
alert("Hello!");
};
EventUtil.addHandler(btn,"click",handler1);
</script>
</html>
使用jQuery,您可以执行以下操作:
<script type="text/javascript">
$(document).ready(function() {
var EventUtil = {
addHandler : function(element, type, handler){
if (element.addEventListener){
element.addEventListener(type,handler,false);
}else if (element.attachEvent){
element.attachEvent("on" + type,handler);
}else{
element["on" + type] = handler;
}
},
removeHandler : function(element, type, handler){
if (element.removeEventListener){
element.removeEventListener(type,handler,false);
}else if (element.detachEvent){
element.detachEvent("on" + type,handler);
}else{
element["on" + type] = null;
}
}
};
var btn = document.getElementById('myBtn');
var handler1 = function(){
alert("Hello!");
};
EventUtil.addHandler(btn,"click",handler1);
};
</script>
答案 1 :(得分:1)
它不起作用,因为输入标记位于脚本标记下,代码将在创建元素之前被执行,因此什么都不起作用。您可以通过在输入标记下放置脚本标记或添加window.onload(){\这里是您的指令}来解决此问题,您可以在其中放置您需要执行的操作,您可以在任何地方初始化函数,但这是你叫他们的地方