繁体   English   中英

blur()和keypress()在使用replacewith()的JQuery上不起作用

[英]blur() and keypress() not working on JQuery with replacewith()

如何在JQuery中将blur()和keypress()事件与replaceWith()同时使用。 我在下面尝试了这段代码,它可以与blur()一起使用,而没有任何错误,只是触发了一个单词“ undefined”,但是当我按下Enter键时,我得到了这个错误:

“未捕获的DOMException:无法在'Node'上执行'replaceChild':要删除的节点不再是该节点的子节点。也许已将其移动到'blur'事件处理程序中?”

这是我的代码:

$('body').on('blur keypress', 'input', function (e) {
  if (e.type === 'focusout' || e.keyCode === 13) {
    $(this).replaceWith('<strong>' + $(this).val() + '</strong>');
  }
});

一旦按下回车键,该元素就会失去焦点,即在移开该元素时会模糊,并触发一个新事件,但是当该事件触发时,该元素将不再在那里,从而导致错误。

您可以通过拆分条件来解决此问题,并在按下Enter键时触发blur事件

$('body').on('blur keypress', 'input', function (e) {
  if ( e.type === 'focusout' ) {
    $(this).replaceWith('<strong>' + $(this).val() + '</strong>');
  }
  if ( e.keyCode === 13 ) {
    $(this).trigger('blur')
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM