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条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)