简体   繁体   中英

Event Handling with JavaScript

I am new to JavaScript and currently learning basics of DOM with event handling. This is my HTML Code:-

<!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>

And, this is my 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;
        }
    }
};

I want to show an alert message when user doesn't click on the link. But, its not working. Am I missing something?

Your code is working if you call

StrayClickCatcher.init();

at the end of your js code. Here is a working copy:

http://jsfiddle.net/DaHHP/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM