简体   繁体   中英

Events are not firing in Jquery UI Tabs

I am using jquery UI tabs in my application. Initially, the tabpane is empty. Tabs gets created dynamically. Each tab has a save button by default. Please look at the following code. Tab appears fine. The problem occurs if I have multiple tabs. For eg: if I have 3 tabs, with 3 save buttons on each of them. Click event fires only from first tab. Event does not fire from any other tabs. I get alerts "from save" and "hello" only when I click save button from first tab. It does not do anything when I click save button from second and third tabs. Can you please tell me if I am missing anything? Thanks.

MyModel = Backbone.Model.extend({

    defaults: {
        name: "Name",
        contents: "<div><table><tr>"+
                "<td><button id='save' value='Save'>Save</button></td>"+
                "</tr></table></div>"

    }

  });



MyView = Backbone.View.extend({


      initialize: function() {
        _.bindAll(this, 'render');
      },
      events: {
            "click #save" : "save"
      },
      save: function(){
        alert("from save");

      },
      render: function() {
        // add the actual content
        $("#tabs").append('<div id="tab_' + this.model.cid + '">'
            + this.model.get('contents')
            + '<br /><br /><br />'
            );

        // ask jQueryUI to add the tab to the bar
        $("#tabs").tabs("add", "#tab_" + this.model.cid, this.model.get('name'));
         $("#save").live("click", function(){
          alert("hello");
        });
        return this;
      }
});


var view = new MyView({ 
                model: model, 
              });
view.render();

IDs should be unique. My guess is that youre creating multiple #save buttons. Try changing it to a class.

On a side note, live() is deprecated. If youre usinga new version of jquery, i would suggest using the on() method. Some psuedo code:

$("#container").on("click", ".savebutton", function(){
      alert("hello");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM