我有以下 jQuery 代码:
$("#contact-form-applet").on("focusout",".dc2-ltfc", {ctx:this},function(event) {
var curRowDiv = $(this);
var rowObject = {};
curRowDiv.find("input, textarea").each(function(e){
rowObject[ $(this).attr("aria-label") ] = $(this).val();
});
console.log(rowObject);
});
问题是每当一个字段失去焦点(字段标签退出)而不是整个 div 失去焦点时都会触发代码。
这是 JS Fiddle link证明问题。
我只想在特定行 div 失去焦点时触发代码,这样我就可以触发更新一次,而不是每次更新行中的字段时。
最佳答案
jquery documentation是这样说的:
The focusout event is sent to an element when it, or any element inside of it, loses focus.
因此,focusout
事件将在每次任何子元素失去焦点时触发。或者,您可以使用 body
的 keyup
和 click
事件通过检查 closest
元素来解决此问题,如下所示:
var previousId=null;
$('body').keyup(function (e) {
var code = e.keyCode || e.which;
if (code == '9') {
focusChange(e);
}
});
$('body').click(function (e) {
focusChange(e);
});
function focusChange(e) {
if (!previousId) {
previousId = $(e.target).closest('.dc2-ltfcc').attr('id');
return;
}
if (previousId != $(e.target).closest('.dc2-ltfcc').attr('id')) {
console.log('Exit');
previousId = null;
}
}
这是 fiddler演示解决方案。
关于javascript - div 上的 focusout 事件未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21872908/