jquery onhover工作,onclick没有

时间:2013-03-04 02:50:34

标签: php javascript jquery

我在漫画网站上添加了喜欢/不喜欢的功能。

我为它制作了自定义图形。

  • 当用户将鼠标悬停在选区上时,它会改变,然后将鼠标悬停交换...

  • 当用户点击时,它会交换图片,直到他们再次点击相同的投票,然后它会切换回原始图像。

enter image description here

on hover工作,但是on on click不...我正试图用Jquery实现这个:

<script type="text/javascript">
  var images = {
      "like": [
        "./images/SiteDesign/like_hover.png",
        "./images/SiteDesign/like.png",
        "./images/SiteDesign/liked.png"         
        ],
      "dislike": [
        "./images/SiteDesign/dislike_hover.png",
        "./images/SiteDesign/dislike.png",
        "./images/SiteDesign/disliked.png"
        ]);

jQuery(document).ready(function($) {
                $("#like, #dislike").hover(function(e) {
                     // mouseover handler
                     if (this.id in images) // check for key in map
                         this.src = images[this.id][0];
                }, function(e) {
                     // mouseout handler
                     if (this.id in images)
                         this.src = images[this.id][1];
                });

                $("#like, #dislike").click(function(e) {
                    alert("clicked");
                    if (this.id in images) // check for key in map
                         this.src = images[this.id][2];
                }, function(e) {
                     // mouseout handler
                     if (this.id in images)
                         this.src = images[this.id][1];
                });                     
            });
</script>

有什么想法?我甚至在点击功能中发出警告(“点击”),但它甚至没有调用它。

1 个答案:

答案 0 :(得分:2)

替换它:

$("#like, #dislike").click(function(e) {
      alert("clicked");
      if (this.id in images) // check for key in map
            this.src = images[this.id][2];
}, function(e) {
      // mouseout handler
      if (this.id in images)
            this.src = images[this.id][1];
});   

用这个:

$("#like, #dislike").click(function(e) {
      alert("clicked");
      if (this.id in images)
            this.src = images[this.id][2];
});   

编辑:

事实上,这样做会更容易:

$("#like, #dislike").on({
    mouseenter: function() {
       if (this.id in images) this.src = images[this.id][0];
    },
    mouseleave: function() {
       if (this.id in images) this.src = images[this.id][1];
    },
    click: function() {
       if (this.id in images) {
           this.src = images[this.id][2];
           $(this).off('mouseenter mouseleave');
       }
    }
});