jQuery值更改事件延迟 [英] jQuery value change event delay

查看:97
本文介绍了jQuery值更改事件延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户完成在文本框中的输入后2秒钟执行一个功能.如果他们在1秒钟后继续键入内容,则延迟时间会重置为2.

I want to execute a function like 2 seconds after a user has finished typing in the textbox. If they continue to type after 1 second, the delay time is reset back to 2.

它的功能应类似于自动填充框.

It should function something similar to an autocomplete box.

我知道2个事件:changekeyup.我在change上遇到的问题是,文本框必须失去焦点才能被触发.对于keyup,如果他们使用鼠标粘贴文本怎么办?

I know of 2 events: change and keyup. The problem I have with change is that the textbox has to loose focus for it to be triggered. for keyup, what if they use the mouse to paste a text?

在这里可以帮我吗?

推荐答案

有HTML5 oninput事件,当前所有主流浏览器均支持该事件,并且可以在IE 8及更低版本中使用:

There's the HTML5 oninput event, supported by all the current major browsers and can be worked into IE 8 and lower:

$("#myInput").bind("input", function () {
    // ...
})

  • http://whattheheadsaid.com/2010/09/effectively-detecting-user -input-in-javascript (解释)
  • http://whattheheadsaid.com/projects/input-special-event (插件)
  • >

    • http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript (explanation)
    • http://whattheheadsaid.com/projects/input-special-event (plugin)
    • 一种非常简单的跨浏览器方法是

      A very simple cross browser approach would be

      $("#myInput").bind("input propertychange", function (evt) {
          // If it's the propertychange event, make sure it's the value that changed.
          if (window.event && event.type == "propertychange" && event.propertyName != "value")
              return;
      
          // Clear any previously set timer before setting a fresh one
          window.clearTimeout($(this).data("timeout"));
          $(this).data("timeout", setTimeout(function () {
              // Do your thing here
          }, 2000));
      });
      

      这将使事件在IE 9中触发两次(对于propertychange来说是一个,对于input来说是一个),但是由于事件处理程序的性质而无关紧要.

      This would make the event fire twice in IE 9 (one for propertychange, one for input), but it doesn't matter because of the nature of the event handler.

      这篇关于jQuery值更改事件延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆