简体   繁体   中英

How to get the jQuery element (or attributes) in a click event in Backbone.js?

I have the following code:

HTML :

<div id='example'>
 <a href='#' data-name='foo' class='example-link'>Click Me</a>
 <a href='#' data-name='bar' class='example-link'>Click Me</a>
</div>

JavaScript

example_view = Backbone.View.extend({
    el: $("#example"),
    events: {
      'click .example-link' : 'example_event'
    },
    example_event : function(event) {
      //need to get the data-name here
    } 
});

how can I get the data-name attribute of the link that was clicked inside of the example_event function ?

Try this.

example_event : function(event) {
  //need to get the data-name here
  var name = $(event.target).data('name');
} 

You can also do this without jQuery using JavaScript's getAttribute method:

example_event : function(event) {
  //need to get the data-name here
  var name = event.target.getAttribute('data-name');
} 

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