【问题标题】:How to trigger an event when the user clears the text field and focus out of the text field using Jquery?当用户清除文本字段并使用 Jquery 将焦点移出文本字段时如何触发事件?
【发布时间】:2015-07-06 10:11:46
【问题描述】:

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

我正在使用以下函数来捕捉“聚焦”事件。

$("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) {
            }
      }
}

但它不起作用。甚至在焦点离开字段之前触发清除字段事件。此外,它多次触发事件。这里有什么问题?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    我认为这更简单:

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

    【讨论】:

    • 我更了解您的问题。试试这个:$('input').on('keyup', function(e) { if(!$(this).val()) { $(this).trigger('blur'); });
    • 所以当用户刚刚离开已经为空的文本框时也会触发。 (实际上没有清算)。
    • 如果用户使用键盘离开输入:是的,但这是一种解决方法检测 TAB 键以避免它。
    • 检测值变化可能是另一种可行的解决方法。用户也可以在其他元素上单击鼠标而不是 TAB 键离开。但是,您的回答是我会采取的解决方案。
    • 你是对的,@Tao。如果他通过 on() 函数中的“更改”来更改“keyup”是更好的解决方案。但是是一个问题,因为当用户输入模糊时会触发“更改”事件,因此该解决方案也无效
    【解决方案2】:

    你在这里:

    $("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" />

    希望这会有所帮助。

    【讨论】:

    • 你是如何制作它的? :|
    猜你喜欢
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    相关资源
    最近更新 更多