当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Backbone.js getting target attribute

问题描述:

I am trying to figure out why the value of e.target.getAttribute('data-text') is becoming null when I go from my HTML to my Backbone JS file.

HTML:

 <script type="text/template" id="lesson-template">

<span id="lesson-title"><%= tracks[0].title %></span>

<select class="sel">

<% _.each(tracks, function(track) { %>

<option value = "<%= track.text %>" data-text="<%= track.title %>"><%= track.title %></option>

<% }); %>

</select>

<p id="tracktext"><%= tracks[0].text %></p>

</script>

JS:

window.LibraryLessonView = LessonView.extend({

events: {

"change .sel " : "changeText"

},

changeText: function(e) {

alert(e.target.getAttribute('data-text')); //I am getting a null value here!

document.getElementById("lesson-title").innerHTML= e.target.getAttribute('data-text'); //I am getting a null value here as well

document.getElementById("tracktext").innerHTML= e.target.value;

}

Any clarification or help will be appreciated!!

网友答案:

The change event will be fired on the <select>, not on the <option>, but your data attributes are on the <option>s. You could dig through $(e.currentTarget) (the <select>) to find the appropriate <option> and then extract the data attributes from there or you could use what you already have.

I would have something like this in the template:

<select class="sel">
    <% _.each(tracks, function(track) { %>
        <option value="<%= track.id %>"><%= track.title %></option>
    <% }); %> 
</select>

No data attributes at all, just a unique track identifier as the <option>'s value. Then when the change event is triggered, you can grab the track ID with:

var id = $(e.currentTarget).val(); // or $(e.target).val() but currentTarget is a bit safer

You should have the track list attached to your view as this.collection so now you can use get to grab the model out of the collection:

var track = this.collection.get(id);

If you don't have ids on your models then you could use the cids that Backbone will create or something else that is unique and findWhere instead of get.

Now that you have the track model in hand, you can pull out the values you want in the usual way:

this.$('#lesson-title').html(track.get('title'));
this.$('#tracktext').html(track.get('text'));

Note that I've switch to this.$, that's a Backbone view function that is equivalent to this.$el.find, localizing your selectors to your view is a good habit.

Demo: http://jsfiddle.net/ambiguous/Jas6c/

网友答案:

You need to wrap jQuery arround to get target.

$(e.target).attr('data-text');
分享给朋友:
您可能感兴趣的文章:
随机阅读: