读书人

JavaScript延时执行function,该怎么处

发布时间: 2012-02-14 19:19:19 作者: rapoo

JavaScript延时执行function
1.当用户输入搜索条件,即打字的时候起开始计时,到停止输入结束,1秒后执行查询function
2.如果1秒内再有输入动作,再重新计时

JavaScript如何实现?

[解决办法]
试试这个

HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title></head><script language="javascript">    function searchKeyWord(id) {        this.element = document.getElementById(id);        this.timeID = null;        this.init();    }    searchKeyWord.prototype = {        init: function() {            var _self = this;            this.element.onkeyup = function() {_self.start()};            this.element.onblur = function() {_self.end()};        },        start: function() {            this.resetTime();            var _self = this;            this.timeID = setTimeout(function(){_self.end()}, 1000);        },        end: function() {            if(this.timeID) {                this.resetTime();                this.searchIt();            }        },        resetTime: function() {            clearTimeout(this.timeID);            this.timeID = null;            },        searchIt: function() {            var _value = this.element.value.replace(/(^\s*)|(\s*$)/g, '');            document.getElementById('t').value = _value;        }    }</script><body><input type="text" id='keyWord' /><input type="text" id='t' /><script language="javascript">    new searchKeyWord('keyWord');</script></body></html>
[解决办法]
JScript code
<script type="text/javascript">var s="";var index = 0;var i = 0;document.onkeypress =function(){        setTimeout("setVal()",1000);    i++;    }function setVal(){    index ++;    if(index==i) {    s = document.getElementById("txt1").value;    alert(s);        index = 0;    i=0;}                }</script><input type=text id="txt1"> 

读书人网 >JavaScript

热点推荐