jQuery'if .change()或.keyup()'

cno*_*gr8 75 javascript jquery function

使用jQuery我想在任何一个.change()或被.keyup()引发时运行一个函数.

像这样的东西.

if ( jQuery(':input').change() || jQuery(':input').keyup() )
{
    alert( 'something happened!' );
}
Run Code Online (Sandbox Code Playgroud)

编辑

对不起,我忘了提.双方.change().keyup()需要一些变量是在范围内.

kee*_*ins 174

您可以通过用空格分隔多个事件来绑定它们:

$(":input").bind("keyup change", function(e) {
    // do stuff!
})
Run Code Online (Sandbox Code Playgroud)

这里的文档.

希望有所帮助.干杯!

  • 请注意,如果值在键盘上发生更改(因此,几乎总是),则会调用内部函数两次.请参阅@Joshua Burns回复来处理它. (7认同)
  • 应该使用.on()而不是.bind() (4认同)

Jos*_*rns 21

If you're ever dynamically generating page content or loading content through AJAX, the following example is really the way you should go:

  1. It prevents double binding in the case where the script is loaded more than once, such as in an AJAX request.
  2. The bind lives on the body of the document, so regardless of what elements are added, moved, removed and re-added, all descendants of body matching the selector specified will retain proper binding.

The Code:

// Define the element we wish to bind to.
var bind_to = ':input';

// Prevent double-binding.
$(document.body).off('change', bind_to);

// Bind the event to all body descendants matching the "bind_to" selector.
$(document.body).on('change keyup', bind_to, function(event) {
    alert('something happened!');
});
Run Code Online (Sandbox Code Playgroud)

Please notice! I'm making use of $.on() and $.off() rather than other methods for several reasons:

  1. $.live() and $.die() are deprecated and have been omitted from more recent versions of jQuery.
  2. 我要么需要定义一个单独的函数(因此混淆全局范围),并将该函数传递给两者$.change()$.keyup()单独传递,或者将相同的函数声明传递给每个被调用的函数; 复制逻辑......这是绝对不可接受的.
  3. 如果元素被添加到DOM中,$.bind()则在创建元素时不会动态绑定到元素.因此,如果绑定到:input然后向DOM添加输入,则该绑定方法不会附加到新输入.然后,您需要显式取消绑定,然后重新绑定到DOM中的所有元素(否则您最终会绑定绑定).每次将输入添加到DOM时,都需要重复此过程.


bre*_*njt 5

做这个。

$(function(){
    var myFunction = function()
    {
        alert("myFunction called");
    }

    jQuery(':input').change(myFunction).keyup(myFunction);
});
Run Code Online (Sandbox Code Playgroud)