我正在尝试通过 .live()
jQuery 方法将一个简单的焦点/模糊事件监听器附加到我的输入,但我注意到的是 focus
事件未触发,而 blur
事件触发。
奇怪……希望您知道为什么会这样。
代码如下:
function rowHighlight() {
var form = $('form.register'),
ele = {};
form.find('label').each(function(i) {
var link = this.htmlFor;
form.find('label[for='+link+'],input[name='+link+'],textarea[name='+link+']').wrapAll('<span class="row"/>');
});
ele.row = $('form > .row');
ele.inputs = ele.row.find('input');
$.each(ele.inputs, function(i) {
$(this).focus(function() {
console.log('hello'); // this will fire.
});
$(this).live('focus blur', function(e) {
console.log('current event type: '+e.type); // the focus on this will not fire!?
( e.type=='focus' ? console.log('focussed') : console.log('blurred') )
});
});
}
rowHighlight();
$(this).focus...
只是把它作为一个调试的东西,删除它不会使 focus
在 live
上听众工作……
如有任何帮助,我们将不胜感激。
感谢您的光临。
詹尼斯
最佳答案
尝试改变这一行:
$.each(ele.inputs, function(i) {
到这一行:
ele.inputs.each(function() {
解释:
jQuery 中的each()
有两种形式。
遍历映射或数组:
$.each([1,2,3], function(index, value){
});
或者,当遍历 jQuery 对象时:
$("a").each(function(){
});
http://api.jquery.com/jQuery.each/
$(this)
表示您仅在第二次使用时才期望的内容:
$("a").each(function(){
$(this).remove();
});
实时与绑定(bind):
$("a").click(someClickEventHandler);
... 将 someClickEventHandler
单击事件处理程序绑定(bind)到执行此操作时存在的每个 a
标记。
$("a").live("click", someClickEventHandler);
... 将 someClickEventHandler
单击事件处理程序绑定(bind)到执行此操作时存在的每个 a
标记,并且还将绑定(bind) someClickEventHandler
单击事件处理程序以处理将永远存在的每个 a
事件。例如,如果 a
标记是从 Ajax 响应创建的,事件处理程序将自动绑定(bind)。
关于Javascript/jQuery : Why is the focus event not firing on an input field?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3722783/