如何委托焦点活动? [英] How to delegate focus event?
问题描述
可能重复:
关注和模糊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将focus
和blur
事件指定为不冒泡,但是jQuery定义了确实会冒泡的跨浏览器focusin
和focusout
事件.当focus
和blur
用于附加委托的事件处理程序时,jQuery映射名称并将其分别作为focusin
和focusout
传递.为了保持一致和清晰,请使用冒泡事件类型名称.
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屋!