本文介绍了2个选择器,2个不同事件,相同功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是jQuery 1.7,需要将相同的函数绑定到2个不同选择器上的2个不同实时事件中,例如:

I'm using jQuery 1.7 and need to bind the same function to 2 different live events on 2 different selectors, like:

function do_something(_this){
  // do something with _this
  alert("test");
}

$("input").live("keyup", function({
  do_something($(this));
});

$("select").live("change", function({
  do_something($(this));
});

这行得通,但是我真的很想如果能以某种方式将所有这些都放入一条语句中,例如:

This works, but I would really like if I could somehow pull all this into one statement, like:

// pseudo code
( $("input").live("keyup") || $("select").live("change") ).bind(function(){
  // do something with $(this)
  alert("test");
});

有可能吗?

推荐答案

您可以将do_something()函数直接放入.live()函数中,并避免使用匿名函数.这样可以节省一些字符.

You can put the do_something() function into the .live() function directly and avoid the anonymous function. That saves a few characters.

$("input").live("keyup", do_something );
$("select").live("change", do_something );

要转换为jQuery 1.7语法,您需要使用一个委托(.live()为您做了).您可以在输入和选择元素所在的位置使用<form>document.

To convert to the jQuery 1.7 syntax, you need to use a delegate (which .live() did for you). You can use the <form> where your input and select elements are or the document.

$( document ).on( "keyup", "input", do_something );
$( document ).on( "change", "select", do_something );

如果您真的想将事件和选择器都放在一个调用中,则可以.由于无论如何都要使用相同的功能,并且由于使用的是委托,因此总共只有两个事件.如果确实认为需要,可以在回调中检查事件,以确保正确的事件与选择器匹配(如我在演示中所示).

And if you really want to put both events and selectors in one call, you can. Since you're going to the same function anyway, and since you're using a delegate there are only two events total. If you really think you need it, you can check the event in the callback to make sure the right one matches the selector (as I show in the demo).

$( document ).on( "keyup change", "input, select", do_something );

演示: http://jsfiddle.net/ThinkingStiff/6ZUMa/

HTML:

<input />
<select>
    <option>1</option>
    <option>2</option>
</select>

脚本:

$( document ).on( 'keyup change', 'input, select', do_something );

function do_something( event ) {

    //this if() statement probably isn't needed for your purposes
    if( ( event.type == 'keyup' && event.target.tagName.toLowerCase() == 'input' )
      || ( event.type == 'change' && event.target.tagName.toLowerCase() == 'select' ) ) {

        //process event here
        $( 'input' ).val( event.type );

    };

};

这篇关于2个选择器,2个不同事件,相同功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:49