Get the clicked object that triggered jquery blur() event [duplicate]

别等时光非礼了梦想. 提交于 2019-11-27 01:31:06
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);
    });​​

});
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);
})

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).

You are handing a blur event, not a click event. So, inside your event, you will have the element that you blured. If you want the clicked element, you'd need another event to get that.

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".

Using this within blur handler function will give you the blured element.

$(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 clicked element you need click event. For example:

$(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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!