【问题标题】:change text and image on click in slideshow在幻灯片中单击更改文本和图像
【发布时间】:2014-11-17 13:21:39
【问题描述】:

我创建了一个幻灯片,可以在点击图像之前和之后切换。我还试图让每个图像的标题在每次点击时同时更改。它适用于每个单独的图像,但是当用户移动到下一张幻灯片时,文本保持在上一张幻灯片的状态。因此,即使所有幻灯片都使用之前的图像开始,如果用户在文本显示为“之后”时前进到下一张幻灯片,它会继续阅读“之后”。

<div class="carousel-inner">
    <div class="item active">
        <img src="imgs/retouched/tattoo_before.jpg" onclick="diffImage1(this)">
        <div class="carousel-caption"><p>Before</p></div>
    </div>
    <div class="item">
        <img src="imgs/retouched/rings_before.jpg" onclick="diffImage2(this)">
        <div class="carousel-caption"><p>Before</p></div>
    </div>
    <div class="item">
        <img src="imgs/retouched/pistol_before.jpg" onclick="diffImage3(this)">
        <div class="carousel-caption"><p>Before</p></div>
    </div>
</div>

如果可能,请让我知道编写这些函数的更简洁的方式。 (我想必须有一种方法可以在一个函数中编写它)。我还尝试编写一个新函数来更改文本,因为每个图像都相同,但我遇到了同样的问题:

function diffImage1(img) {
    if (img.src.match("_before")) {
        img.src = "imgs/retouched/tattoo_after.jpg";
        $(".carousel-caption p").html("After");
    } else {
        img.src = "imgs/retouched/tattoo_before.jpg";
        $(".carousel-caption p").html("Before");
    }
   }

    function diffImage2(img) {
        if (img.src.match("_before")) {
            img.src = "imgs/retouched/rings_after.jpg";
            $(".carousel-caption p").html("After");
        } else {
            img.src = "imgs/retouched/rings_before.jpg";
            $(".carousel-caption p").html("Before");
        }
    }

    function diffImage3(img) {
        if (img.src.match("_before")) {
            img.src = "imgs/retouched/pistol_after.jpg";
            $(".carousel-caption p").html("After");
        } else {
            img.src = "imgs/retouched/pistol_before.jpg";
            $(".carousel-caption p").html("Before");
        }
    }

【问题讨论】:

    标签: javascript jquery onclick slideshow image-replacement


    【解决方案1】:

    像这样将它们组合成一个函数

    $("div.carousel-inner div.item img").on("click", function(){
        if ($(this).src.match("_before")) {
            $(this).src = "imgs/retouched/pistol_after.jpg";
            $(this).parent().find("p").html("After");
        } else {
            $(this).src = "imgs/retouched/pistol_before.jpg";
            $(this).parent().find("p").html("Before");
        }
    }
    

    imgs 上不再需要 onclick=

    【讨论】:

      【解决方案2】:

      使用 find() 选择器查找下一个p 然后更改文本

        $(img).next(".carousel-caption").find( "p").text("After");
      

      DEMO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-11
        • 1970-01-01
        • 2014-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多