简体   繁体   English

点击jQuery图片交换

[英]Jquery Image Swap on Click

This is an image link in the HTML document that is supposed to change the image when clicked. 这是HTML文档中的图像链接,应该在单击时更改图像。 As you can figure out, it could be one of the 2 images. 如您所知,它可能是2张图像之一。 Timeline-hand or hand-clicked. 手动或单击时间轴。 When someone clicks, if the src is timeline-hand it should change it to hand-clicked and vice versa. 当某人单击时,如果src是时间轴手动的,则应将其更改为手动单击,反之亦然。

Problem is, that it is only working once. 问题是,它只能工作一次。 That is, when the page loads and you click on the hand, it changes the picture the first time, but does not revert it back when you click it again. 也就是说,当页面加载并且您单击手上时,它将第一次更改图片,但是当您再次单击它时不会将其还原。

$("document").ready(function(e) {

    $("#timeline-link").click(function(e){
        if ($("#timeline-hand").attr("src","images/timeline-hand.gif"))
        {
            $("#timeline-hand").attr("src","images/hand-clicked.gif");
        }

    else if ($("#timeline-hand").attr("src","images/hand-clicked.gif"))
        {
            $("#timeline-hand").attr("src","images/timeline-hand.gif");
        }
    });
});

The setter version of jQuery returns a jQuery object which is always truthy. jQuery的setter版本返回始终是真实的jQuery对象。 You need to use the getter version of jQuery and then check the returned value like if ($("#timeline-hand").attr("src") == "images/timeline-hand.gif") 您需要使用jQuery的getter版本,然后检查返回的值,例如if ($("#timeline-hand").attr("src") == "images/timeline-hand.gif")

Or 要么

$(function() {
  $("#timeline-link").click(function(e) {
    $("#timeline-hand").attr("src", function(i, src) {
      return src == "images/timeline-hand.gif" ? 'images/hand-clicked.gif' : "images/timeline-hand.gif";
    })
  });
});
$( "#target" ).toggle(function() {
     $("#timeline-hand").attr("src","images/timeline-hand.gif");
 }, function() {
     $("#timeline-hand").attr("src","images/hand-clicked.gif");
});

I'll see more something like this : 我会看到更多类似这样的内容:

$("document").ready(function(e) { 
    $("#timeline-link").click(function(e){ 
        var attr = $("#timeline-hand").attr("src");
        if (attr == "images/timeline-hand.gif") { 
            $("#timeline-hand").attr("src","images/hand-clicked.gif"); 
        } else if (attr == "images/hand-clicked.gif") { 
            $("#timeline-hand").attr("src","images/timeline-hand.gif"); 
        } 
    }); 
});

Try this 尝试这个

$(document).ready(function() {     
  $('#timeline-link').click(function() {
    $('img', this).attr('src', function(i, oldSrc) {
        return oldSrc == 'images/timeline-hand.gif' ? 'images/timeline-hand.gif' : 'images/timeline-hand.gif';
    });
    return false;
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM