如何委托焦点活动? [英] How to delegate focus event?

查看:89
本文介绍了如何委托焦点活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
关注和模糊jQuery事件不冒泡

Possible Duplicate:
Focus and blur jQuery events not bubbling

var default_input_value = null;
jQuery('body').on('focus focusout', 'input[type="text"]', function(event){
    if(event.type === 'focus'){
        default_input_value = jQuery(this).val();
        jQuery(this).val('');
    }else if(event.type === 'focusout')
        if(jQuery(this).val().length === 0)
        jQuery(this).val(default_input_value);
    }
);

此代码根本不响应事件. P.S.

This code simply does not respond to the event. P.S. it is important that there would be input[type="text"], because jQuery focus also fires on checkbox in some situations....

推荐答案

.on() jQuery文档中,有一个说明:

Under .on() jquery document, there is a description:

W3C将focusblur事件指定为不冒泡,但是jQuery定义了确实会冒泡的跨浏览器focusinfocusout事件.当focusblur用于附加委托的事件处理程序时,jQuery映射名称并将其分别作为focusinfocusout传递.为了保持一致和清晰,请使用冒泡事件类型名称.

The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble. When focus and blur are used to attach delegated event handlers, jQuery maps the names and delivers them as focusin and focusout respectively. For consistency and clarity, use the bubbling event type names.

希望这会很有用.

您可以尝试以下代码:

var default_input_value = null;
jQuery('body').on('focusin focusout', 'input[type="text"]', function(event){
    if(event.type === 'focusin'){
        default_input_value = jQuery(this).val();
        jQuery(this).val('');
    }else if(event.type === 'focusout'){
        if(jQuery(this).val().length === 0)
        jQuery(this).val(default_input_value);
    }
});

这篇关于如何委托焦点活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆