单击鼠标时使用JQuery进行图像交换

时间:2013-01-28 23:00:46

标签: javascript jquery

我想在JavaScript中使用jQuery替换另一个图像。它是一个在线巴士预订网站。因此,当点击可用图像时,它应该变为不可用图像。有谁知道这件事。

2 个答案:

答案 0 :(得分:0)

您可以这样做:

$('#myImage').on('click', function(e) {
    var image = this;
    img.src = '/path/to/another/image.png';
});

此外,如果您有一堆需要交换的图像,最好使用事件委派。让我们假设这些可交换图像可以在页面的任何位置,并为所有这些图像分配swappable类。然后,您可以设置一个事件处理程序来处理交换,即使您使用AJAX动态添加新图像:

$(document).on('click', 'img.swappable', function(e) {
    var image = this;
    image.src = getAvailableImageUrl();
});

答案 1 :(得分:0)

有很多方法,以下是一些方法。

<img id="bannerLogo" src="/path/to/image/logoup.png" />
<script type="text/javascript">
var imageCounter = 0;
$('#bannerLogo').click(function(){
    if(imageCounter%2==0){
        $('#bannerLogo').attr('src', '/path/to/image/logodown.png');
    }
    else {
        $('#bannerLogo').attr('src', '/path/to/image/logoup.png');
    }
    imageCounter++;
});
</script>

(注意 - 从jQuery 1.7开始,不推荐使用.live()方法。使用.on()来附加事件处理程序。旧版jQuery的用户应优先使用.delegate(),而不是.live()。 )

<img class="swapper" src="imagename_off.jpg"  />
<script type="text/javascript">
$(function(){
  $(".swapper").live('click', function() {
    if ($(this).attr("class") == "swapper") {
      this.src = this.src.replace("_off","_on");
    } else {
      this.src = this.src.replace("_on","_off");
    }
    $(this).toggleClass("on");
  });
});
</script>

我希望这会有所帮助。

我还会添加我的悬停脚本,以防您在某些时候需要它:

$('#bannerLogo').hover(
      function() { $('#bannerLogo').attr('src', '/path/logodown.png');}, 
      function() { $('#bannerLogo').attr('src', '/path/logoup.png'); 
});     

不要忘记包含JQuery lib

http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js

谢谢, 菲利普

相关问题