【问题标题】:jquery change or toggle images when clicked单击时jquery更改或切换图像
【发布时间】:2013-04-09 01:09:25
【问题描述】:

我正在尝试做一个“单击 image1 时显示 image2,单击 image2 时显示 image3,单击 image3 时显示 image1...”的事情。

它适用于 2 张图片 - image1 转到 2,image2 转到 1,依此类推,但是当引入第三张图片时,它会变得混乱。我的代码是:

 <img id ="rotate_images" src="img1_on.png"/>

<script>

$('#rotate_images').on({
    'click': function() {
         var src = ($(this).attr('src') === 'img1_on.png')
            ? 'img2_on.png'
            : 'img1_on.png';
         $(this).attr('src', src);
         var src = ($(this).attr('src') === 'img2_on.png')
            ? 'img3_on.png'
            : 'img2_on.png';
         $(this).attr('src', src);

     }

});

我有点知道为什么会这样 - image1 转到 image3,因为它跳过了第一个代码块,而 image3 转到 image2,出于同样的原因,但是......我可以添加一些东西来修复它吗?感谢您的帮助。

克里斯。

【问题讨论】:

    标签: jquery image toggle


    【解决方案1】:

    固定代码:

    <img id ="rotate_images" src="img1_on.png"/>
    
    <script>
    $('#rotate_images').on({
        'click': function () {
            var origsrc = $(this).attr('src');
            var src = '';
            if (origsrc == 'img1_on.png') src = 'img2_on.png';
            if (origsrc == 'img2_on.png') src = 'img3_on.png';
            if (origsrc == 'img3_on.png') src = 'img1_on.png';
            $(this).attr('src', src);
        }
    });
    </script>
    

    【讨论】:

    • 完美!正是我想要的。
    • @ChristopheHarris 希望将其标记为答案
    【解决方案2】:

    您可以使用ifelse if。它仅在第一个条件为假时检查第二个条件,如果两个条件都不为真则进入else

    $('#rotate_images').on({
        'click': function() {
             var newSrc,
                 src = $(this).attr('src');
             if (src === 'img1_on.png') {
                 newSrc = 'img2_on.png';
             } else if (src === 'img2_on.png') {
                 newSrc = 'img3_on.png';
             } else {
                 newSrc = 'img1_on.png';
             }
             $(this).attr('src', newSrc);
         }
    });
    

    但是,如果您想要一个更具可扩展性的解决方案,您可以制作一个使用数组的通用算法:

    var imageSrcs = ['img1_on.png', 'img2_on.png', 'img3_on.png'];
    
    $('#rotate_images').on({
        'click': function() {
             // find index of src within the array
             var index = imageSrcs.indexOf($(this).attr('src'));
             if (index < 0 || index == (imageSrcs.length - 1)) {
                 // reset to first image
                 index = 0;
             } else {
                 // go to next image
                 index++;
             }
             $(this).attr('src', imageSrcs[index]);
         }
    });
    

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      相关资源
      最近更新 更多