Question

Please bear with me, I've just started playing with js/jQuery.

I have a dynamically generated menu and wish to apply background images to each li based on the link text. The text I can get with .text, and inserting the images is no problem either - I just need to find out to have the script stop and insert the corresponding image at each li. I expected .each to do this but the following code runs through then applies the image for the last li to all of them.

<script type="text/javascript">
    $(function() {
        $('#CategoryList li a').each(function() {               
            $('#CategoryList li').css('background','url(http://my_site.com/images/'+ (this).text +'.png) no-repeat');
        });
    });                            
</script>

Clearly I'm missing something basic (arrays perhaps?). All help appreciated.

Was it helpful?

Solution

Use $(this).text() instead of (this).text

 $('#CategoryList li').css('background','url(http://my_site.com/images/'+ $(this).text() +'.png) no-repeat');

As per my understanding you need

$(function () {
    $('#CategoryList li a').each(function () {
        $(this).closest('li').css('background', 'url(http://my_site.com/images/' + $(this).text() + '.png) no-repeat');
    });
});

OTHER TIPS

Use $(this).text() This will return current a element text

Try this

 $('#CategoryList li').css('background','url(http://my_site.com/images/'+ $(this).text() +'.png) no-repeat');

(this).text is not working please put $(this).text()

$(function() {
    $('#CategoryList li a').each(function() {               
        $('#CategoryList li').css('background','url(http://my_site.com/images/'+ $(this).text() +'.png) no-repeat');
    });
}); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top