例子很简单,记录点击的次数。 有意思的地方,是在对于DOM节点,js是如何控制的。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>click</title>
</head>
<body>
<button id="clickme">Click me: 0</button>
<script>
function myHandler(e) {
var src, parts;
// get event and source element
e = e || window.event;
src = e.target || e.srcElement;
// actual work: update label
parts = src.innerHTML.split(": ");
parts[1] = parseInt(parts[1], 10) + 1;
src.innerHTML = parts[0] + ": " + parts[1];
// no bubble
if (typeof e.stopPropagation === "function") {
e.stopPropagation();
}
e.cancelBubble = true;
// prevent default action
if (typeof e.preventDefault === "function") {
e.preventDefault();
}
e.returnValue = false;
}
var b = document.getElementById('clickme');
if (document.addEventListener) { // W3C
b.addEventListener('click', myHandler, false);
} else if (document.attachEvent) { // IE
b.attachEvent('click', myHandler);
} else { // last resort
b.onclick = myHandler;
}
</script>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>click</title>
</head>
<body>
<div id="click-wrap">
<button>Click me: 0</button>
<button>Click me too: 0</button>
<button>Click me three: 0</button>
</div>
<script>
function myHandler(e) {
var src, parts;
// get event and source element
e = e || window.event;
src = e.target || e.srcElement;
// actual work: update label
parts = src.innerHTML.split(": ");
parts[1] = parseInt(parts[1], 10) + 1;
src.innerHTML = parts[0] + ": " + parts[1];
// no bubble
if (typeof e.stopPropagation === "function") {
e.stopPropagation();
}
e.cancelBubble = true;
// prevent default action
if (typeof e.preventDefault === "function") {
e.preventDefault();
}
e.returnValue = false;
}
var el = document.getElementById('click-wrap');
if (document.addEventListener) { // W3C
el.addEventListener('click', myHandler, false);
} else if (document.attachEvent) { // IE
el.attachEvent('click', myHandler);
} else { // last resort
el.onclick = myHandler;
}
</script>
</body>
</html>