简体   繁体   中英

How to set DIV background-image css jquery?

Motto is to set/update(ajaxified) a DIV background image.

        $.getJSON("https://itunes.apple.com/search?term=" + searchTerm + '&limit=1' + '&callback=?', 
        function(data) {
        $.each(data.results, function() {
        var art = this.artworkUrl100;
        $('.photo').parent().css('background-image', 'url(' + art + ')');
      }
    }

On HTML i've this:

<div id="results" class="photo"></div>

You are setting the background image to a parent element instead of the .photo div.

Try this:

$.getJSON("https://itunes.apple.com/search?term=" + searchTerm + '&limit=1' + '&callback=?', 
    function(data) {
        $.each(data.results, function() {
            var art = this.artworkUrl100;
            $('.photo').css('background-image', 'url(' + art + ')');
        })
});

If multiple data.results are returned then only the last be used for the background image due to the $.each loop that you are using. If you are maintaining the limit=1 on the JSON call then this won't be a problem.

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