1. 程式人生 > >JS自定義事件繫結--通過URL觸發不同的點選事件

JS自定義事件繫結--通過URL觸發不同的點選事件

window.onload = function () { var btn1 = document.getElementById("btn1"); var btn2 = document.getElementById("btn2"); function EventTarget () { this.handlers = {}; // 物件屬性,有三個方法 // this.handlers = { // type1 : [type1Fun1, type1Fun2], // type2 : [type2Fun1, type2Fun2]
// } } EventTarget.prototype = { constructor : EventTarget, /**繫結事件 * param type : 自定義事件型別 * param handler : 自定義事件繫結的回撥函式 */ addHandler : function (type, handler) { // 如果傳入的事件型別為undefined,就建立一個數組 if (typeof this.handlers[type] == "undefined"
) { this.handlers[type] = []; } // 再將回調函式新增到陣列中去 this.handlers[type].push(handler); }, /**觸發事件 * param event : 傳入的物件 * { type : "show", message : "hello world"} */ fire : function (event) { if
(!event.target) { event.target = this; } if (this.handlers[event.type] instanceof Array) { var handlers = this.handlers[event.type]; for (var i = 0, len = handlers.length; i < len; i++) { handlers[i](event); // 呼叫對應事件的回撥函式 } } else { throw new Error("No event can call"); } }, /**登出事件的回撥函式 * param type : 事件型別 * param handler : 回撥函式 * 呼叫示例:removeHanlder("show", showMessage); * 登出show型別的showMessage函式 **/ removeHandler : function (type, handler) { if (this.handlers[type] instanceof Array) { var handlers = this.handlers[type]; // 取得對應事件的回撥函式 for (var i = 0, len = handlers.length; i < len; i++) { if (handlers[i] == handler) { break; // 得到對應事件的索引值 } } handlers.splice(i, 1); // 刪除索引值,即刪除對應的事件的其中一個回撥函式 } } } function btn1Fun(){ alert("btn1Fun"); } var btn2Fun = function (){ alert("btn2Fun"); } var eventTarget = new EventTarget(); // 獲取請求的引數 var request = window.location.search.substring(1); // 獲取value值 var value = request.split("=")[1]; // 通過遍歷button觸發事件 var input = document.getElementsByTagName("input"); for (var i = 0, len = input.length; i < len; i++) { if (value === input[i].value) { eventTarget.addHandler("click", eval(value + "Fun")); eventTarget.fire({ type : "click"}); } } }