如何触发一个事件,当用户清除文本字段和焦点的文本字段使用Jquery

How to trigger an event when the user clears the text field and focus out of the text field using Jquery?

本文关键字:字段 文本 清除 焦点 Jquery 用户 何触发 事件 一个      更新时间:2023-09-26

当用户清除文本字段并移出焦点时,我需要编写一个事件处理程序。

我使用下面的函数来捕捉"focus out"事件。

$("input[type=text]").blur(function () {
}

我有以下函数来捕获清除字段事件。

$("input[type=text]").keyup(function() {
            if (!this.value) {
     }
}

我尝试在blur()中使用keyup()函数,因为我需要捕捉焦点,然后清除字段。我的代码是这样的:

$("input[type=text]").blur(function () {
$(this).keyup(function() {
            if (!this.value) {
            }
      }
}

但是它不起作用。清除字段事件甚至在焦点离开字段之前被触发。而且,它会多次触发事件。这里的问题是什么?

我觉得这样更简单:

$('input').on('blur', function(e) {
    if(!$(this).val()) {
         // IS NO VALUE IN THE INPUT
         $(this).trigger('blur'); // trigger the blur event
    }
});

给你:

$("input[type=text]").on('blur', function() {
  alert('blur');
});
$("input[type=text]").on('input', function() {
  if (!$(this).val()) {
    alert("input nothing");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />