【发布时间】:2023-03-24 02:23:02
【问题描述】:
鉴于以下标记,我想检测编辑器何时失去焦点:
<div class="editor">
<input type="text"/>
<input type="text"/>
</div>
<div class="editor">
<input type="text"/>
<input type="text"/>
</div>
<button>GO</button>
编辑:当用户在输入元素中切换并且每个编辑器 div 失去焦点(意味着他们在 div 之外切换)时,将加载类添加到失去焦点的 div。
这点 jquery 是我期望的,但它什么也没做:
$(".editor")
.blur(function(){
$(this).addClass("loading");
});
这似乎有效,直到您添加控制台日志并意识到它会在输入的每个焦点输出时触发。
$('div.editor input').focus( function() {
$(this).parent()
.addClass("focused")
.focusout(function() {
console.log('focusout');
$(this).removeClass("focused")
.addClass("loading");
});
});
Here is a jsfiddle 我一直在处理的测试用例。我知道我在这里遗漏了一些基本的东西。哪位大神可以解惑一下?
编辑:在下面的一些 cmets 之后,我几乎可以按照我想要的方式工作。现在的问题是检测焦点何时更改到编辑器 div 之外的某个地方。这是我当前的实现:
function loadData() {
console.log('loading data for editor ' + $(this).attr('id'));
var $editor = $(this).removeClass('loaded')
.addClass('loading');
$.post('/echo/json/', {
delay: 2
})
.done(function () {
$editor.removeClass('loading')
.addClass('loaded');
});
}
$('div.editor input').on('focusin', function () {
console.log('focus changed');
$editor = $(this).closest('.editor');
console.log('current editor is ' + $editor.attr('id'));
if (!$editor.hasClass('focused')) {
console.log('switched editors');
$('.editor.focused')
.removeClass('focused')
.each(loadData);
$editor.addClass('focused');
}
})
有点复杂,并且使用类来表示状态。我还添加了下一点复杂性,即当编辑器失去焦点时进行异步调用。 Here a my jsfiddle 我目前的工作。
【问题讨论】:
-
虽然这个问题是关于检测焦点丢失的,但它比链接的问题要具体得多。
-
你应该使用捕获而不是冒泡,并防止在 div 上传播,你得到了我相信的所有子事件,让我试试。
-
是的,因为就像文档中所说:当元素或其中的任何元素失去焦点时,将焦点事件发送到元素。这与 blur 事件不同,它支持检测对后代元素失去焦点(换句话说,它支持事件冒泡)。
-
你不能使用
blur,因为div不是form的一部分。
标签: javascript jquery