Does binding events to elements in jQuery multiple times have a knock on effect?

前端 未结 2 719
暗喜
暗喜 2021-01-17 14:47

If I have the below code, textboxes of class serial will be bound to the events more than once if the new serial button is pressed multiple times.

Will this hinder

2条回答
  •  花落未央
    2021-01-17 15:03

    You can bind multiple event handlers to a single element. The following would produce a button with two onclick events:

    $("button").bind("click", myhandler);
    $("button").bind("click", myhandler);
    

    One option would be to unbind the events first:

    $("button").unbind("click").bind("click", myhandler);
    $("button").unbind("click").bind("click", myhandler);
    

    This will result in only a single bound click event.

    If you're rebinding the events because your form has dynamically added elements, then you might want to look into live() or the new on(), which can bind events to elements that might not yet exist. Example:

    $("button").live("click", myhandler); // All buttons (now and in 
                                          // the future) have this handler.
    

    In the Webkit Developer Tools (Safari and Chrome), you can see what events are bound to an element by inspecting it, then scrolling down in the right pane of the Elements panel. It's under a collapsable box named 'Event Listeners'. Firebug should have similar functionality.

提交回复
热议问题