开发者

jQuery - Adding same actions for multiple events & Binding

开发者 https://www.devze.com 2023-02-24 06:02 出处:网络
I\'ve been trying to find a way to add the same action for multiple events. I have the following action assigned to #comid (which is a select menu).

I've been trying to find a way to add the same action for multiple events.

I have the following action assigned to #comid (which is a select menu).

$("#comid").change(function()
{
    comid = $("#comid").val();
    //alert(comid);

    $('#com_photo').addClass('loading');

    $('#com_photo').load('ajax.php?requestType=ajax&action=get_com_photo&comid=' + comid, function() {
        $('#com_photo').removeClass('loading');
        $('#com_photo img').hide();
        $('#com_photo img').fadeIn(1000);
        alert('Image Loaded.');
    });
});

Now, the above code works well. When the user selects an item from the select menu the change event is triggered and the ajax request is made开发者_Python百科 and the image is showed along with a alert window saying "Image Loaded".

But, i want the same action to trigger if the user doesn't use the mouse and instead is using keyboard keyup/keydown to select from the menu. It doesn't do that by default which i hoped it did but that doesnt seem to be the case so i want to assign the same action for the keyup or keydown event but i dont want to write (or copy/paste) the same code over again.

After a while of searching i found out about the bind(), i tried do it like this:

$("#comid").bind('keyup',function(event){
    $("#comid").trigger('change');
}

It works, but when i use the keyup, i see the alert window twice saying "Image Loaded", so i find that behavior unwanted since it seems like it is making the request twice.

Is there something i am doing wrong? or are there any better alternatives to what i'm trying to accomplish?

Thanks in advance :)


$("#comid").bind('change keyup', function(){
    ...
});

You can attach your function to multiple events like this. Check the documentation for bind, it's pretty useful.

You may also want to read about live. It does (pretty much) the same thing as bind, but the function will be applied to any newly created (matching) elements as well.

Edit: for your select menu, the function will fire twice if you use the arrow keys to select an option. In your case, you should just use change(). Keyup() is not needed.


You can bind multiple events with live():

$("#comid").live({
  click: function(){/* code */},
  change: function(){/* code */}
});

You can then just wrap your script into a function and call that function at all events.

More info at jQuery API.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号