1. 程式人生 > 實用技巧 >input輸入框延時防抖

input輸入框延時防抖

    <body>
        <div class="firstBox">
            <div class="box">
                <div class="btn"></div>
                <input type="text" id="cph" value="" />
            </div>
            <div class="content">
            </div>
        </
div> </body> <script type="text/javascript"> var oInp = document.getElementById("cph"); oInp.oninput = debounce(ajax, 1000); function debounce(handler, delay) { var timer = null; // 返回函式引用 return function() {
var _self = this; var _args = arguments; clearTimeout(timer); timer = setTimeout(function() { /*改變handler的this指向。 * handler的this指向當前返回的函式引用,例如:oInp.oninput = debounce(ajax, 1000); * 此時this就是指向oInp.oninput了
*/ handler.apply(_self, _args); }, delay); } } function ajax(e) { console.log(e + " " + this.value); } </script>