开发者

Grouping of jQuery's events

开发者 https://www.devze.com 2023-03-21 08:37 出处:网络
Can you group jQuery\'s events like with switch();? Something like: $(element).bind({ blur: keyup: function(){ /* both do the same stuff */ }

Can you group jQuery's events like with switch();?

Something like:

$(element).bind({
    blur:
    keyup: function(){ /* both do the same stuff */ }
    /* Update below */
    click: function(){ /* specific stuff */ },
    mouseenter: functio开发者_Python百科n() { /* more specific stuff */ }
});


You can use the bind method to group jQuery events:

$("myItem").bind("click blur keyup", myFunction);

UPDATE

Having read a little more into the bind method since your update, it seems that since jQuery 1.4 we can do exactly what you're asking for:

$('#foo').bind({
  click: function() {
    // do something on click
  },
  mouseenter: function() {
    // do something on mouseenter
  }
});

Taken from: http://api.jquery.com/bind/#multiple-events

I notice now that it's not exactly as you're asking. What you can do is assign the same function to different events but as far as I can tell, there no way to do a direct chaining of events using this method. I tried bind({click, blur: function(){}}) for example and a few other ways but none of them seem to work.


No, but you can do this to make the code more concise:

function myFunction(){ /* stuff to do */ }

...

onblur: myFunction,
onkeyup: myFunction,


I came across this question while searching for a similar way to do this to - i have found using the code below worked for me - note, this will only work if you are using jquery 1.7+

$("#someID").on("keyup click change blur", function() {

//whatever to be run goes here

});

Just wanted to add this in here in case it helps people running a more recent jquery version :)


No but you can string them together - $().blur(process).keyup(process), and define the functionality in process separate.

Linking them in the fall-through way is not possible - although if you want to write a plug in....


$("#foo").bind( "blur keyup click mouseenter", function(event) {
    switch(event.type) {
        case "blur":
        case "keyup": alert('first'); break;
        case "click": alert('click' ); break;
        case "mouseenter": alert('mouse'); break;
        default: break;
    }
});

You can bind the four events in the function call, then use a regular javascript switch statement on event.type to handle the different cases.

0

精彩评论

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