Javascript 获取触发 jquery blur() 事件的点击对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11544554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the clicked object that triggered jquery blur() event
提问by pillarOfLight
Suppose I do this:
假设我这样做:
$(target).blur(function(e){
//do stuff
});
Is there a way to fetch the object that was clicked on in order to trigger the blur action?
有没有办法获取被点击的对象以触发模糊动作?
I tried using e.target
, but that appears to be returning the object attached to the blur action rather than the clicked object.
我尝试使用e.target
,但这似乎是返回附加到模糊动作的对象而不是单击的对象。
采纳答案by daryl
If I understand your question correctly, this should do it:
如果我正确理解您的问题,则应该这样做:
$(function() {
var clicky;
$(document).mousedown(function(e) {
// The latest element clicked
clicky = $(e.target);
});
// when 'clicky == null' on blur, we know it was not caused by a click
// but maybe by pressing the tab key
$(document).mouseup(function(e) {
clicky = null;
});
$(target).blur(function(e) {
console.log(clicky);
});??
});
回答by blockhead
The trick is to wait an extra tick:
诀窍是等待一个额外的滴答声:
$(el).blur(function (event) {
// If we just hangout an extra tick, we'll find out which element got focus really
setTimeout(function(){
document.activeElement; // This is the element that has focus
},1);
})
回答by Rocket Hazmat
Inside an event handler, this
will be the element the event is bound to, and e.target
will be the element that triggered the event (may or not be the same as this
).
在事件处理程序中,this
将是事件绑定到e.target
的元素,并将是触发事件的元素(可能与 相同,也可能不同this
)。
You are handing a blur
event, not a click
event. So, inside your event, you will have the element that you blur
ed. If you want the click
ed element, you'd need another event to get that.
您正在处理一个blur
事件,而不是一个click
事件。因此,在您的事件中,您将拥有您blur
编辑的元素。如果你想要click
ed 元素,你需要另一个事件来获得它。
blur
can be triggered by other events, such as focusing something; not just clicking on something. So, there is no way to get the element that "caused the blur".
blur
可以由其他事件触发,例如聚焦某物;不只是点击某些东西。因此,无法获取“导致模糊”的元素。
回答by thecodeparadox
Using this within blur
handler function will give you the blured
element.
在blur
处理程序函数中使用 this将为您提供blured
元素。
$(target).blur(function(e){
var bluredElement = this; // dom element
// To make a jQuery object
var bluredElement = $(this);
});
Within blur
event you can't catch the clicked element. To get the click
ed element you need click
event. For example:
在blur
事件中,您无法捕获单击的元素。要获取click
ed 元素,您需要click
事件。例如:
$(element).click(function() {
var clickedElement = this;
});
And to get the focused element you can use :focus
selector like: $(':focus')
will returns you focused element in document.
要获得焦点元素,您可以使用:focus
选择器,例如:$(':focus')
将在文档中返回焦点元素。