开发者

call the same function on many events

开发者 https://www.devze.com 2023-01-08 20:14 出处:网络
i need to call the same function on many events开发者_开发百科 $(\"#test1\").click(function(){ some_function();

i need to call the same function on many events开发者_开发百科

$("#test1").click(function(){
some_function();
});
$("#test1").hover(function(){
some_function();
})

how can i write this with one function?


That seems messy. I believe this should work.

$('#test1').bind('click mouseenter mouseleave', some_function);

Remember that .hover() takes two functions as arguments, so having only one function could produce unexpected results.


You could put all the events in an array, and for each element add your function.

Example:

events=[ $("#test1").click, $("#test1").hover ];

for ( e in events ) {
  e( some_function );
};


$('#test1').bind('click hover', function() { some_function(); });

http://api.jquery.com/bind/

0

精彩评论

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