代码之家  ›  专栏  ›  技术社区  ›  Matthew

jquery-为文本字段“changing”构建事件?(按键工作,除了没有退格事件)

  •  2
  • Matthew  · 技术社区  · 15 年前

    我知道我可以解释“backspace”键。

    任何 将输入中的文本更改为触发“事件”或调用刷新函数。

    思想?

    2 回复  |  直到 15 年前
        1
  •  2
  •   Peter Ajtai    12 年前

    为了确保每次更改文本字段后都触发数据搜索,应检查每次更改后文本字段是否已更改 .keyup() .keydown()

    // The following only works for keyboard input, to handle mouse copy / paste
    // see the example after this
    $(function() {                         // <== Doc ready  
    
        var inputVal = $("input").val();   // a variable to hold the text
                                           // set it up w the initial value then see 
                                           // if the input value changes.
    
        $("input").keyup(function() {
    
            // check for change of the text field after each key up
            if(this.value != inputVal)
            {
                // Do your search, etc.
                // ...
    
                // Reset the temp value for the next comparison
                inputVal = this.value
            }
        });
    });
    

    Try it out with this jsFiddle

    为了处理鼠标复制粘贴(Filipe指出这一点与上面的操作不兼容),jQuery可以选择将多个事件绑定到一个元素,并且它有一个 paste cut

    $(function() {    // <== Doc ready  
    
        var inputVal = $("input").val(), // a variable to hold the text
                                         // set it up w the initial value then see 
                                         // if the input value changes.
    
            timer,
            checkForChange = function() {
                var self = this; // or just use .bind(this)
    
                // we only want to check on the input after the user has settled down,
                // so use a timeout and clear it if another input comes in
                if (timer) { clearTimeout(timer); }
    
                // check for change of the text field after each key up
                timer = setTimeout(function() {
                    if(self.value != inputVal) {
                        // Do your search, etc.
                        $("span").html(parseInt($("span").html(),10) + 1);
    
                        // Reset the temp value for the next time
                        inputVal = self.value
                    }
                }, 250);
            };
    
        $("input").bind('keyup paste cut', checkForChange);
    });
    

    现在我们检查键盘,粘贴和剪切。

    Try it out with this jsFiddle


        2
  •  0
  •   SamB som-snytt    15 年前

    Common event behaviors (这是关于不同类型的 input change 活动应该做你想做的事。(无论如何,这几十年中的一年)处理这个事件至少应该是安全的,即使许多浏览器还不支持它。