简体   繁体   中英

How can I prevent child click event bubbling to parent?

I'm new to Backbone and here is my situation:

I've a table and I want each rows get highlighted when they are clicked. Each cells also contain some hyperlinks. The problem is when I try to click on the links, the cell get highlighted also, which is not what I want. I can find a workaround, which is to bind a 'click' event to all the hyperlinks (refer to the 'dummy' function below) and then use e.stopPropagagtion(). That works, but it seems that it's not a clean way to do so, any recommendations? Thanks!

样品

Here is my table row view

app.UserRowView = Backbone.View.extend({
  el: '',
  tagName:'tr',
  className:'badge-user-row',
  template: twig({ data: $("#jsid-table-row").html() }),
  model: null,
  events: {
    'click' : 'rowClicked',
    'click a': 'dummy',
  },
  initialize: function(user) {
    this.model = user;
    this.listenTo(this.model, 'change', this.render);
  },
  render: function() {
    var html = this.template.render({ user: this.model.toJSON() });
    this.$el.html(html);
    return this;
  },
  rowClicked: function(e) {
      console.log(e.currentTarget);
      this.$el.toggleClass('row-selected');
  },
  dummy: function(e) {
    e.stopPropagation();
  }
});

And my table row template:

    <td class="badge-cell"><input type="checkbox"></input></td>
    <td class="badge-cell">
      <div>{{ user.name }}</div>
      <a href="javascript:void(0)">Link 1</a>
    </td>
    <td class="badge-cell">
      {{ user.age }}
      <a href="http://google.com.hk">Link 2</a>
    </td>

如何在您的jQuery选择器中包含一个not呢?

$("#jsid-table-row:not(a)").html()

 rowClicked: function(e) { console.log(e.currentTarget); if($(e.target).is("a") { this.dummy() } else { this.$el.toggleClass('row-selected'); } }, 

And delete "'click a': 'dummy'" part . I think it will be working

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