<!doctype html>
<html>
<head>
<title></title>
<!--binding handlers to object-->
<script type="text/javascript">
<!--
function showAuthor()
{
alert("oscar wilde");
}
function enableEvent()
{
document.getElementById('someText').attachEvent("onmouseover",showAuthor);
}
function disableEvent()
{
someText.detachEvent("onmouseover",showAuthor);
}
//-->
</script>
</head>
<body onload="enableEvent();">
<em id="someText">we may be in the gutter ,but some of us are looking at the stars</em>
<form action="#" method="get">
<input type="button" value="Attach event" onclick="enableEvent();" />
<input type="button" value="Detach event" onclick="disableEvent();" />
<input type="button" value="show author" onclick="showAuthor();" />
</form>
</body>
</html>
我已经使用上面的代码来实现事件处理程序,但是当我执行程序时,事件处理程序没有附加。为什么呢?
答案 0 :(得分:0)
此
document.getElementById('someText').attachEvent("onmouseover",showAuthor);
应该是这样的
document.getElementById('someText').addEventListener("mouseover",showAuthor, false);
您不想附加活动,但想要添加事件监听器。
此外,您不想分离任何事件,但是您想要删除一个事件侦听器,其语法如下:
document.getElementById("someText").removeEventListener("mouseover",showAuthor, false);
var someText = document.getElementById("someText");
function showAuthor(){
alert("oscar wilde");
}
function enableEvent(){
someText.addEventListener("mouseover",showAuthor, false);
}
function disableEvent(){
someText.removeEventListener("mouseover",showAuthor, false);
}
<body onload="enableEvent()">
<em id="someText">we may be in the gutter ,but some of us are looking at the stars</em>
<form action="#" method="get">
<input type="button" value="Attach event" onclick="enableEvent()" />
<input type="button" value="Detach event" onclick="disableEvent();" />
<input type="button" value="show author" onclick="showAuthor()" />
</form>
</body>
有关上述内容的详细说明,请查看以下链接:
答案 1 :(得分:0)
我猜你需要使用addEventListener
。使用addEventListener
时,您无需在&#34;上使用&#34;带有事件名称的前缀。
<强> 段: 强>
<script type="text/javascript">
function showAuthor() {
alert("oscar wilde");
}
function enableEvent() {
document.getElementById('someText').addEventListener('mouseover', showAuthor);
}
function disableEvent() {
document.getElementById('someText').removeEventListener('mouseover', showAuthor);
}
</script>
<body onload="enableEvent();">
<em id="someText">we may be in the gutter ,but some of us are looking at the stars</em>
<form action="#" method="get">
<input type="button" value="Attach event" onclick="enableEvent();" />
<input type="button" value="Detach event" onclick="disableEvent();" />
<input type="button" value="show author" onclick="showAuthor();" />
</form>
&#13;
希望这有帮助。