jQuery Event Handler created in loop

前端 未结 4 1851
别那么骄傲
别那么骄傲 2020-11-30 06:59

So I have a group of events like this:

$(\'#slider-1\').click(function(event){   
        switchBanners(1, true);
});
$(\'#slider-2\').click(function(event){         


        
4条回答
  •  心在旅途
    2020-11-30 07:15

    [edit: saw this answer get an upvote and recognized it's using old syntax. Here's some updated syntax, using jQuery's "on" event binding method. The same principle applies. You bind to the closest non-destroyed parent, listening for clicks ON the specified selector.]

    $(function() {
      $('.someAncestor').on('click', '.slider', function(e) {
        // code to do stuff on clicking the slider. 'e' passed in is the event
      });
    });
    

    Note: if your chain of initialization already has an appropriate spot to insert the listener (ie. you already have a document ready or onload function) you don't need to wrap it in this sample's $(function(){}) method. You would just put the $('.someAncestor')... part at that appropriate spot.

    Original answer maintained for more thorough explanation and legacy sample code:


    I'm with tereško : delegating events is more powerful than doing each click "on demand" as it were. Easiest way to access the whole group of slider elements is to give each a shared class. Let's say, "slider" Then you can delegate a universal event to all ".slider" elements:

    $(function() {
        $('body').delegate('.slider', 'click', function() {
            var sliderSplit = this.id.split('-'); // split the string at the hyphen
            switchBanners(parseInt(sliderSplit[1]), true); // after the split, the number is found in index 1
        });
    });
    

    Liddle Fiddle: http://jsfiddle.net/2KrEk/

    I'm delegating to "body" only because I don't know your HTML structure. Ideally you will delegate to the closest parent of all sliders that you know is not going to be destroyed by other DOM manipulations. Often ome sort of wrapper or container div.

提交回复
热议问题