简体   繁体   中英

Setting background image with jQuery not working

Good Day

I want to dynamically set the background images on a div, inside a li element, so that I do not have to specify each div's background image individually....

My code (JS) however,is not working. Also see my FIDDLE

HTML:

<div id="imageWrapper">
    <ul>
        <li>
            <div></div> <span></span>

        </li>
        <li>
            <div></div> <span></span>

        </li>
        <li>
            <div></div> <span></span>

        </li>
        <li>
            <div></div> <span></span>

        </li>
    </ul>
</div>

CSS

#imageWrapper ul li div {
    width: 65px;
    height: 65px;
    background-position: center center;
}

JS

$(document).ready(function () {
    var length = 4; //This is the number of images I have to add
    for (i = 0; i < length; i++) {
        $('#imageWrapper ul li div').css('background', 'url(/path/images/' + i '.jpg)');
    }
});

Also, this list of images I want to load is pretty big. What is the best way to load so many images and populate them in the DOM without having to write out all the html and css - thats just stupid

Thank you

You can do it with this code, but it's not recommended to handle this with JavaScript if you have to touch up that many elements to change their backgrounds.

$(document).ready(function () {
    $('#imageWrapper ul li').each(function(i){
        $(this)
            .find('div')
            .css('background-image', 'url(/path/images/' + (i+1) + '.jpg)');
    });
});

Here is an example of the PHP method.

<?php 
  echo '<div id="imageWrapper"><ul>';
    $i=4;
      while($i-->0){
       echo '<li class="background-'.$i.'"><div></div><span></span></li>'.PHP_EOL;
      }
  echo '</ul></div>';
?>

It prints out 4 <li> s with the div and span. You would still have to add background with CSS.

The elements print out .background-1 , .background-2 , so you can just make background changes by editing the class quick and easy.

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