2012-05-09 16 views
21

Ho il seguente codice:Come ottenere l'elemento jQuery (o gli attributi) in un evento click in Backbone.js?

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 
    } 
}); 

come posso ottenere l'attributo data-name del legame che è stato cliccato all'interno della example_event funzione ?

risposta

40

Prova questo.

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

lavorato per me, troppo! – HPWD

17

È anche possibile fare questo senza jQuery usando il metodo di JavaScript getAttribute:

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

Questo ha funzionato per me usando CoffeeScript, la risposta accettata no. – crmpicco

+0

entrambe le risposte funzioneranno bene se convertite correttamente in coffeescript –