假设我在一个HTML输入框上附加了一个模糊函数,如下所示:
<input id="myInput" onblur="function() { ... }"></input>
是否有一种方法来获得导致模糊事件的元素的ID(被点击的元素)在函数内?如何?
例如,假设我有这样一个张成的空间:
<span id="mySpan">Hello World</span>
如果我在输入元素有焦点之后点击span,输入元素将失去它的焦点。该函数如何知道被单击的是mySpan ?
PS:如果跨度的onclick事件发生在输入元素的onblur事件之前,我的问题就解决了,因为我可以设置一些状态值,指示特定的元素已被单击。
PPS:这个问题的背景是,我想从外部触发一个AJAX自动补全控件(从一个可点击的元素)来显示它的建议,而不会因为输入元素上的模糊事件而立即消失建议。因此,我想检查是否有一个特定的元素被单击了模糊函数,如果是这样,忽略模糊事件。
我也试图使自动补全器忽略模糊,如果一个特定的元素点击,并有一个工作的解决方案,但只有Firefox由于显式originaltarget
Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap(
function(origfunc, ev) {
if ($(this.options.ignoreBlurEventElement)) {
var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode : ev.explicitOriginalTarget);
if (!newTargetElement.descendantOf($(this.options.ignoreBlurEventElement))) {
return origfunc(ev);
}
}
}
);
This code wraps default onBlur method of Autocompleter and checks if ignoreBlurEventElement parameters is set. if it is set, it checks everytime to see if clicked element is ignoreBlurEventElement or not. If it is, Autocompleter does not cal onBlur, else it calls onBlur. The only problem with this is that it only works in Firefox because explicitOriginalTarget property is Mozilla specific . Now I am trying to find a different way than using explicitOriginalTarget. The solution you have mentioned requires you to add onclick behaviour manually to the element. If I can't manage to solve explicitOriginalTarget issue, I guess I will follow your solution.