【发布时间】:2013-05-17 13:41:43
【问题描述】:
我正在尝试在 JavaScript 中启用事件处理。这是我目前所拥有的:
function Field(args) {
this.id = args.id;
this.name = args.name ? args.name : null;
this.reqType = args.reqType ? args.reqType : null;
this.reqUrl = args.reqUrl ? args.reqUrl : null;
this.required = args.required ? true : false;
this.error = args.error ? args.error : null;
this.elem = document.getElementById(this.id);
this.value = this.elem.value;
this.elem.addEventListener('onblur', this, false);
this.elem.addEventListener('click', this, false);
this.elem.addEventListener('change', this, false);
console.log(JSON.stringify(this.elem.value));
}
function FormTitle(args) {
Field.call(this, args);
}
Field.prototype.getValue = function() { return Helpers.trim( this.value ) };
Field.prototype.sendRequest = function () {
};
Field.prototype.click = function (value) {
alert("click");
};
Field.prototype.onblur = function (value) {
alert("onblur");
};
Field.prototype.change = function (value) {
alert("change");
};
Field.prototype.dblclick = function (value) {
alert("dblclick");
};
Field.prototype.handleEvent = function(event) {
switch (event.type) {
case "click": this.click(this.value);
case "onblur": this.onblur(this.value);
case "change": this.change(this.value);
case "dblclick": this.dblclick(this.value);
}
};
// inheritProtootype uses parasitic inheritance to inherit from the Field's prototype
// and then assign the results to FormTitle's prototype.
inheritPrototype(FormTitle, Field);
var title = new FormTitle({name: "sa", id: "title"});
但是,由于某种原因,所有事件都会同时触发。例如,当我点击Form中的Title字段时,不是只触发Click事件,而是触发了所有四个事件。
我做错了什么?
【问题讨论】:
-
this.elem.addEventListener('…', this, false);确实附加了Field实例,一个对象,作为事件侦听器 - 这需要是一个函数吗?
标签: javascript events javascript-events event-handling