I have a list of images, one of which gets a class="selected" after a change occurs on the page:
<div id="selectable">
<li>
<img src="\images\1.jpg" />
</li>
<li class="selected">
<img src="\images\2.jpg" />
</li>
<li>
<img src="\images\3.jpg" />
</li>
</div>
I want to be able to capture the value of the image's src attribute, so I can use it later... I'm thinking something like this:
$("#selectable").change(function() {
var src = $('li[class="selected"]').attr('src');
alert("source of image with alternate text = example - " + src);
}
But I need it to get the value of the src attribute of the child element (img).
I have a list of images, one of which gets a class="selected" after a change occurs on the page:
<div id="selectable">
<li>
<img src="\images\1.jpg" />
</li>
<li class="selected">
<img src="\images\2.jpg" />
</li>
<li>
<img src="\images\3.jpg" />
</li>
</div>
I want to be able to capture the value of the image's src attribute, so I can use it later... I'm thinking something like this:
$("#selectable").change(function() {
var src = $('li[class="selected"]').attr('src');
alert("source of image with alternate text = example - " + src);
}
But I need it to get the value of the src attribute of the child element (img).
Share Improve this question asked Aug 26, 2013 at 5:39 Jet59blackJet59black 1391 silver badge15 bronze badges6 Answers
Reset to default 2 $("li.selected").find("img").attr("src");
You can do this using below code.
var src = $('li.selected img').attr('src');
-------------^^^^^^^^^^^^^^^--------
I want to be able to capture the value of the image's src attribute, so I can use it later...
var src = ''; // DEFINE VARIABLE OUTSIDE
$('#selectable li').click(function(){ // USE CLICK EVENT
src = $('img', this).attr('src');
// alert( src )
});
To target directly the desired image use:
// some event
$('#selectable li.selected img').attr('src');
//
var imgsrc="";
$("#selectable li").click(function() {
var imgsrc= $('li.selected img').attr('src');
alert( imgsrc);
}
Change
var src = $('li[class="selected"]').attr('src');
to
var src = $('li[class="selected"]').find('img').attr('src');
More on jQuery find
You need to do something like this:
var src=$('#selectable > li.selected > img').attr('src');
alert("source of image with alternate text = example - " + src);
An example
HTML:
<div id="selectable">
<li>
<img src="\images\1.jpg" />
</li>
<li class="selected">
<img src="\images\2.jpg" />
</li>
<li>
<img src="\images\3.jpg" />
</li>
</div>
Javascript:
$('#selectable li').click(function(){
$(this).addClass('selected');
var src = $(this).children('img').attr('src');
alert("source of image with alternate text = example - " + src);
});
See Jquery selector techniques for more details: http://api.jquery./category/selectors/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745565363a4633361.html
评论列表(0条)