我是JavaScript的新手,目前正在学习具有事件处理功能的DOM基础知识。
这是我的HTML代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<title>My Test Program for Event Handler</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>The first captain of the USS Enterprise NCC-1701 was
<a id="t1" href="http://en.wikipedia.org/">My Link!</a>.</p>
<script type="text/javascript" src="example.js"></script>
</body>
</html>
而且,这是我的Jscript:
var StrayClickCatcher = {
init: function () {
var links = document.getElementsByTagName("a");
if (typeof document.addEventListener != "undefined") {
document.addEventListener("click", StrayClickCatcher.strayClickListener, false);
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("click", StrayClickCatcher.linkClickListener, false);
}
} else if (typeof document.attachEvent != "undefined") {
document.attachEvent("onClick", StrayClickCatcher.strayClickListener);
for (var i = 0; i < links.length; i++) {
links[i].attachEvent("onClick", StrayClickCatcher.linkClickListener);
}
}
},
strayClickListener: function (event) {
alert("Did you mean to click a link? " + "It's that blue, underlined text.");
},
linkClickListener: function (event) {
if (typeof event == "undefined") {
event = window.event;
}
if (typeof event.stopPropagation != "undefined") {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
};
我想在用户未单击链接时显示警报消息。但是,它不起作用。我想念什么吗?
最佳答案
如果您拨打电话,代码就可以正常工作
StrayClickCatcher.init();
在您的js代码的末尾。这是一个工作副本:
http://jsfiddle.net/DaHHP/