我正在尝试在 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"});
但是由于某种原因,所有事件都会同时触发。例如,当我单击表单中的“标题”字段时,不是仅触发 Click 事件,而是触发所有四个事件。
我做错了什么?
最佳答案
简单。在每个 case
block 的末尾,使用 break;
语句将其与每个后续 block 分开。
关于javascript - 使用原型(prototype)继承在 Javascript 中进行事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16610574/