【问题标题】:Jquery change image source depending on id of div clickedJquery 根据单击的 div 的 id 更改图像源
【发布时间】:2011-11-29 19:37:04
【问题描述】:

我希望单击拇指以显示带有预加载器的较大图像,然后在加载完成时淡入。

感谢this answer - 它可以根据单击的拇指来加载不同的图像 - 以及 this guide 解决加载位。

结合两者我有以下脚本:

 <script type="text/javascript">
    <!--
    $(function () {
        $('img[id^="thumb"]').click(function () {
        $('#loader').show();
        var id = $(this).attr('id').replace('thumb', '');
        var img = new Image();
        $(img).load(function () {
            //$(this).css('display', 'none');
            $(this).hide();
            $('#loader').removeClass('loading').append(this);
            $(this).fadeIn();
        }).attr('src', 'photos/1.jpg');
    }); });

    //-->
    </script>

最后您会注意到 .attr 源固定在一张图像上。我想要的是“.jpg”之前的数字根据拇指的 id 而变化(它们被标记为:“thumb1”、“thumb2”等)

有没有办法做到这一点?非常感谢!

ps This answer 似乎很接近,但我遇到的问题是拇指 id 在脚本中似乎为时过早,无法使用如此简单的解决方案。

【问题讨论】:

  • 我建议您看一下 Javascript Closures,这将消除您对“thumb id 在脚本中似乎太早而无法使用如此简单的解决方案”的困惑

标签: jquery swap thumbnails


【解决方案1】:
<script type="text/javascript">

    $(function () {
        $('img[id^="thumb"]').click(function () {
        var thumbId = $(this).attr('id').substring(5); // assuming the id of the thumb is like "thumb1", "thumb2", ...
        $('#loader').show();
        var id = $(this).attr('id').replace('thumb', '');
        var img = new Image();
        $(img).load(function () {
            //$(this).css('display', 'none');
            $(this).hide();
            $('#loader').removeClass('loading').append(this);
            $(this).fadeIn();
        }).attr('src', 'photos/' + thumbId + '.jpg');
    }); });


    </script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多