仅现代浏览器
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}
doc.addEventListener('click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault();
doSomething.call(e.target, e);
}
});
})(document);
function doSomething(event){
console.log(this);
}
</script>
</head>
<body>
<button class="click-me">Button 1</button>
<input class="click-me" type="button" value="Button 2">
</body>
</html>
跨浏览器
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var cb_addEventListener = function(obj, evt, fnc) {
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, false);
return true;
}
else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
}
else {
evt = 'on'+evt;
if(typeof obj[evt] === 'function'){
fnc = (function(f1,f2){
return function(){
f1.apply(this,arguments);
f2.apply(this,arguments);
}
})(obj[evt], fnc);
}
obj[evt] = fnc;
return true;
}
return false;
};
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}
cb_addEventListener(doc, 'click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault ? e.preventDefault() : e.returnValue = false;
doSomething.call(e.target, e);
}
});
})(document);
function doSomething(event){
console.log(this);
}
</script>
</head>
<body>
<button class="click-me">Button 1</button>
<input class="click-me" type="button" value="Button 2">
</body>
</html>
您可以在文档准备好之前运行此程序,因为我们将事件附加到文档上,所以单击按钮将起作用。
资料来源: