JavaScriptのイベントハンドラ処理プログラム(イベントリスナー)

参考コード:
<html>
<head>
<title>event util test</title>
<script type="text/javascript">
var eventUtil = {
addListener: function(element, type, hander) {
if (element.addEventListener) {
element.addEventListener(type, hander, false);
} else if (element.attachEvent) {
element.attachEvent('on’ + type, hander);
} else {
element['on’ + type] = hander;
}
},
getEvent: function(event) {
return event || window.event;
//return event ? event : window.event;
},
getTarget: function(event) {
return event.target || event.srcElement;
},
preventDefault: function(event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
removeListener: function(element, type, hander) {
if (element.removeEventListener) {
element.removeEventListener(type, hander, false);
} else if (element.deattachEvent) {
element.detachEvent(type, hander);
} else {
element['on’ + type] = null;
}
},
stopPropagation: function(event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
};
</script>
</head>
<body>
<input type="button" value="クリックしてください" id="btn" />
<a href="http://www.arkgame.com">arkgame.com</a>
<script type="text/javascript">
(function() {
var btn = document.getElementById(“btn");
var link = document.getElementsByTagName(“a")[0];
eventUtil.addListener(link, “click", function(event) {
alert(“prevent default event");
var event = eventUtil.getEvent(event);
eventUtil.preventDefault(event);
});
eventUtil.addListener(btn, “click", function(event) {
var event = eventUtil.getEvent(event);
var target = eventUtil.getTarget(event);
alert(event.type);
alert(target);
eventUtil.stopPropagation(event);
});
eventUtil.addListener(document.body, “click", function() {
alert(“click body");
});
})();
</script>
</body>
</html>

JavaScript

Posted by arkgame