简体   繁体   中英

Getting the src attribute of an image within a parent tag

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).

 $("li.selected").find("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');
//

You can do this using below code.

var src = $('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.com/category/selectors/

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