jQuery: Is it illegal or bad practice to assign mu

2019-04-12 21:57发布

Possible Duplicate:
jQuery: more than one handler for same event

I am using a jQuery slider plugin that creates two buttons. These buttons have click events attached to them by the plugin as they are used to control the slider. I have created my own mouseover\mouseout events independent of the plugin (inline with the webpage) to handle animations. I would like to create one for click as well (so that the button changes color). Will me creating another click event handler override or break what the plugin does? Is it bad practice and is there a better way?

5条回答
地球回转人心会变
2楼-- · 2019-04-12 22:09

Having two events is no problem. You can assign as many events to an object as you like.

This is logical as you most likely want different functions to fire depending on the event that's triggered. And 99% of every jQuery-plugin will have no problem dealing with objects with multiple events. Try it and ask a question if you have any problems.

The only thing that is not good is inline js ;)

查看更多
爷、活的狠高调
3楼-- · 2019-04-12 22:09

Not really, though if you can handle all functionality in one handler, then why wouldn't you?

查看更多
我只想做你的唯一
4楼-- · 2019-04-12 22:12

In some cases I would say it is bad practice. Creating multiple event handlers on a single element is almost always avoidable. If you are comfortable enough, you could always open the source of the plugin(if its not a minified version) and modify the event handler to include your modifications.

If you are uncomfortable doing that, then I would say continue what you are doing. Just know that there are better alternatives.

This assumes that you are adding say another click event binding when the plugin already has one.

-Mike

查看更多
你好瞎i
5楼-- · 2019-04-12 22:18

It would NOT break any handler that was bound already. The way jQuery bind is using event registration model and so it support multiple event handlers.

This is one of the advantages in using addEventListeners/attachEvent over traditional methods.

More reading: https://stackoverflow.com/a/12627478/297641

查看更多
男人必须洒脱
6楼-- · 2019-04-12 22:19

You should have no problem. Just add your own event handler using jQuery's API and you'll be set. From the jQuery Docs on .on():

As of jQuery 1.4, the same event handler can be bound to an element multiple times.

$('#myButton').on('click', myHandler)
查看更多
登录 后发表回答