简体   繁体   中英

find img in div and read alt text

I would like to find an image in an animated <div class="text_slider"> and read the alt="" of it.

<div id="slider">
   <img src="1.png" alt="this is the first image" />
   <img src="2.png" alt="this is the second image" />
</div>

My attempt was:

function afterPic() { 
    $('.text_slider').animate({
            opacity: 0.25,
            height: 'toggle'
        }, 1000, 
        function() {
          $('.text_slider').html("<p style='z-index: 9998;'>"
                 + $('#slider').find('img').this.alt +"</p>"); 
        }
    );

but unfortunately it does not work.

You forgot the quotes around '#slider' and are using jQuery wrong...

It will do the trick: $('#slider').find('img').attr('alt')

OK, two things.

You reference the class .text_slider that doesn't exist in your markup and your div has an id of #slider . To get the alt in jQuery, you should use the prop() function. alt is a property of a JavaScript DOM object, not a jQuery object.

function afterPic() { 
    $('.text_slider').animate({
        opacity: 0.25,
        height: 'toggle'
    }, 1000, function() {
           $('.text_slider').html("<p style='z-index: 99998;'>" + 
           $('#slider').find('img').prop('alt') + ":</p>"); 
    });
}

DEMO: http://jsfiddle.net/abc123/FJfTb/

To find an item under another item you should always apply the parent selector:

$('#slider > img').attr('alt');

the > shows that #slider is the parent to the img.

HTML:

<div id="slider">
    <img src="1.png" alt="this is the first image" />
    <img src="2.png" alt="this is the second image" />
</div>

JS:

alert($('#slider > img').attr('alt'));

As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes. So if you are using jQuery newer than 1.6 please replace attr with prop

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