dongyou6847 2014-02-21 11:51
浏览 146
已采纳

jquery更改div的背景图片点击

I have 10 small pictures across the bottom of the screen and one main picture. What I am trying to achieve is having the main picture replaced by one of the 10 small pictures, when they are clicked on.

Code so far is:

$(function () {
    $('#sp<?php echo $i; ?>').on {
        'click', (function () {
            $('#product-detail-pic').css('background-image', 'url(images/stock/<?php echo $stock[1][pic.$i]; ?>');
        });
    }
);

and the HTML/PHP is

<?php for($i=1;$i<6;$i++) {
    if(($stock[1]['pic'.$i]!='')) { ?>
        <div id="sp<?php echo $i; ?>" style="padding-right:13px; width:84px;    height:61px; background:url(images/stock/<?php echo $stock[1]['pic'.$i]; ?>) no-repeat;float:left; background-size:84px 61px;">
            <img src="images/zoom.png" width="40" height="30" />
        </div>                      
<?php }
  • 写回答

3条回答 默认 最新

  • douyan6871 2014-02-21 15:30
    关注

    I don't recommend doing it this way as you need to bind the event handlers on each thumbnail, and that's not efficient. It's better if you put the thumbnail ID on the HTML tag instead of binding the click event on each thumbnail.

    Your PHP code should look like this:

    <?php
    for( $i=1; $i<6; $i++ ) {
        if( $stock[1]['pic'.$i] != '' ) { ?>
            <div data-img-url="<?php echo $stock[1]['pic'.$i] ?>" style="padding-right:13px; width:84px; height:61px; background:url(images/stock/<?php echo $stock[1]['pic'.$i]; ?>) no-repeat;float:left; background-size:84px 61px;">
                <img src="images/zoom.png" width="40" height="30" />
            </div>
        }
    }
    ?>
    

    and your jQuery event handler should look something like this:

    $(function () {
        $( '[data-img-url]' ).on( 'click', function () {
            $('#product-detail-pic').css('background-image', $( this ).data( 'img-url' ) );
        });
    });
    

    No messing with PHP on the JS side, much cleaner and efficient :)

    I'm using '[data-img-url]' as a jQuery selector just for this example. On your site, you should be using a selector that's relevant to the thumbnails.

    For example, if your thumbnails are placed in a container with the thumbnails ID, then you could do:

    $( "#thumbnails" ).on( 'click', '[data-img-url]', function() {
        $('#product-detail-pic').css('background-image', $( this ).data( 'img-url' ) );
    } );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?