Reputation: 565
I have a code like this
<ul class="dd-menu">
<li>
<a href="#"><span><img src="{{STATIC_URL}}img/away.png"></span>1</a>
</li>
<li>
<a href="#"><span><img src="{{STATIC_URL}}img/inacall.png"></span>2</a>
</li><ul>
Javascript
menuApp = Backbone.View.extend({
el: $('#header-status'),
events: {
'click .dd-menu li a': 'optionChange'
},
optionChange: function(e) {
var selectedItemText = $(e.currentTarget).text();
var selectedItemSrc = $(e.currentTarget).data("src");
console.log($(e.currentTarget).data("src")); //Undefined
$("#availability").text(selectedItemText);
$("#availabilitySRC").attr("src").replace(selectedItemSrc); //Error
}});
I am trying to show selected li and now it shows text of selected li. However, It is not showing image of selected item. Is there a way to get src of img?
Thanks
Upvotes: 0
Views: 1558
Reputation: 97717
Your anchors have no data-src
attribute and no src
attribute(which is what I think you actually want to get), try selecting the image and getting its src attribute
optionChange: function(e) {
var selectedItemText = $(e.currentTarget).text();
var selectedItemSrc = $(this).find('img').attr("src");
console.log(selectedItemSrc);
$("#availability").text(selectedItemText);
$("#availabilitySRC").attr("src", selectedItemSrc);
}
https://api.jquery.com/data/
https://api.jquery.com/attr/
Upvotes: 0
Reputation: 3594
Your error while getting src
is that you are referencing to a tag. You must reference to img tag. To do this:
optionChange: function(e) {
var $a = $(e.currentTarget); // get a tag
var $img = $a.find('img'); // find img in a tag
var selectedItemText = $a.text(); // text from a
var selectedItemSrc = $img.attr('src'); // src from img
$("#availability").text(selectedItemText); // set text
$("#availabilitySRC").attr('src', selectedItemSrc); // set src attr
}});
To get attribute from element use attr('attribute-name')
function.
To change attribute value use attr('attribute-name', newValue)
. replace
if used to replace whole elements.
Upvotes: 3