一、前言

1、 element.addEventListener(eventType, handler, capture);

(1)参数eventType是要注册句柄的事件类型名。

(2)参数handler是句柄函数,在指定类型事件发生时调用该函数。

(3)参数capture用于在事件传播的捕获阶段事件句柄是否用于捕捉事件。

2、element.attachEvent("on" + eventType, handler);

该方法作为全局函数调用,而不是作为事件句柄所注册的元素的方法来调用的。允许同一个事件句柄函数多次注册。

3、相关自定义类Binder代码如下:

 (function (window) {
if (!window.jasen) {
window.jasen = {};
} if (!window.jasen.core) {
window.jasen.core = {};
} if (!window.jasen.core.Binder) {
window.jasen.core.Binder = {};
} if (typeof jasen.core.Binder != "object") {
throw new Error("Invalid entity jasen.core.Binder!");
} function bind(element, eventType, handler, capture) {
if (typeof element == "string") {
element = document.getElementById(element);
} if (typeof capture != "Boolean") {
capture = false;
} if (element.addEventListener) {
element.addEventListener(eventType, handler, capture); // Allow to register the same event handler only one.
}
else if (element.attachEvent) {
if (capture) {
element.setCapture();
} element.attachEvent("on" + eventType, handler); // Allow to register the same event handler more times.
}
else {
element["on" + eventType] = handler; // Non support Capture.
}
} function unbind(element, eventType, handler, releaseCapture) {
if (typeof element == "string") {
element = document.getElementById(element);
} if (typeof releaseCapture != "Boolean") {
releaseCapture = false;
} if (element.removeEventListener) {
element.removeEventListener(eventType, handler, releaseCapture);
}
else if (element.detachEvent) {
if (releaseCapture) {
element.releaseCapture();
} element.detachEvent("on" + eventType, handler);
}
else {
element["on" + eventType] = null;
}
} function cancelBubble(e) {
e = e || window.event; if (e.stopPropagation) {
e.stopPropagation();
}
else {
e.cancelBubble = true; //IE
}
} var binder = window.jasen.core.Binder;
binder.bind = bind;
binder.unbind = unbind;
binder.cancelBubble = cancelBubble; window.Binder = binder; })(window);

二、范例

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jasen.core.Binder.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="test" value="bind element"/>
</div>
<script type="text/javascript">
jasen.core.Binder.bind("test", "click", function () { alert("....."); }, true);
</script>
</form>
</body>
</html>
05-06 06:34