焦点上触发模糊事件 [英] Blur event triggered on focus
问题描述
我使用以下代码 jsFiddle :
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('blur', this, false);
this.elem.addEventListener('focus', this, false);
}
// FormTitle is the specific field like a text field. There could be many of them.
function FormTitle(args) {
Field.call(this, args);
}
Field.prototype.getValue = function() { return Helpers.trim( this.value ) };
Field.prototype.blur = function (value) {
alert("blur");
};
Field.prototype.focus = function (value) {
alert("focus");
};
Field.prototype.handleEvent = function(event) {
var prop = event.type;
if ((prop in this) && typeof this[prop] == "function")
this[prop](this.value);
};
inheritPrototype(FormTitle, Field);
var title = new FormTitle({name: "sa", id: "title"});
function inheritPrototype(e, t) {
var n = Object.create(t.prototype);
n.constructor = e;
e.prototype = n
}
if (!Object.create) {
Object.create = function (e) {
function t() {}
if (arguments.length > 1) {
throw new Error("Object.create implementation only accepts the first parameter.")
}
t.prototype = e;
return new t
}
}
问题是每当场上的模糊事件被激发时,这与您期待的相反。这是尽管在代码中甚至没有提到焦点事件。问题是我无法在jsFiddle中复制这个问题,但问题出现在IE中。
The problem is that the 'blur' event is fired every time the field is brought to focus, which is opposite of what you'd expect. This is despite the fact that the focus event isn't even mentioned in the code. The problem is that I cannot replicate this problem in jsFiddle but the problem is happening in IE.
另外,在jsFiddle上还有另一个问题。焦点事件多次被触发...
Also, on jsFiddle, there is another problem. The focus event is triggered multiple times...
是否有可能的解释和/或解决方案?
Is there a possible explanation for this and/or a solution?
奖金问题(最后一个,承诺)。
我添加了一个函数addEvent来动态添加事件来形成字段,而不是直接在父构造函数中添加它们。这是 jsFiddle 。我试图调用该函数,但似乎不起作用。我可能会做错什么?
Bonus question (and last on this, promise). I added a function addEvent to dynamically add events to form fields instead of adding them all directly in the parent constructor. This is the jsFiddle for it. I am trying to call the function but it doesn't seem to work. What might I be doing wrong?
推荐答案
alert
code> focus 处理程序在获取焦点后立即将焦点从该字段中移除。焦点失去触发 blur
。很奇怪, blur
首先出现。
The alert
in your focus
handler immediately removes focus away from the field as soon as it gains focus. The loss of focus triggers the blur
. It is odd that the blur
comes first.
如果将警报更改为控制台.log
(或某些不会重点关注的东西),您将看到事件正常启动。
If you change the alerts to console.log
(or something that does not steal focus), you will see that the events fire correctly.
这篇关于焦点上触发模糊事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!