更改图像单击按钮

Change images clicking button

我无法完成这项工作....当我们点击另一张图片时,我必须使用 jquery 来更改一张图片;所以,我有 4 个人,他们有 3 张图片,每张图片都有他们最喜欢的东西。有两个图像作为按钮;一颗心和一个盘子。默认情况下,它必须显示 3 个喜爱的事物,如果我们单击心形图像将显示,如果我们单击盘子图像,它将把这 3 个图像更改为他们最喜欢的食物的 3 个图像。

html

<div id="steve" class="ourLove">
   <img class="love1" />
   <img class="love2" />
   <img class="love3" />
   <img class="heart" />
   <img class="plate" />
</div>
<div id="betty" class="ourLove">
   <img class="love1" />
   <img class="love2" />
   <img class="love3" />
   <img class="heart" />
   <img class="plate" />
</div>
<div id="glen" class="ourLove">
   <img class="love1" />
   <img class="love2" />
   <img class="love3" />
   <img class="heart" />
   <img class="plate" />
</div>
<div id="maria" class="ourLove">
   <img class="love1" />
   <img class="love2" />
   <img class="love3" />
   <img class="heart" />
   <img class="plate" />
</div>

这是我的js

jQuery(document).ready(function() {     
   jQuery('.plate', this).click(function() {
     jQuery('.love1', this).attr('src', 'images/food1.jpg');
     jQuery('.love2', this).attr('src', 'images/food2.jpg');
     jQuery('.love3', this).attr('src', 'images/food3.jpg');
        return false;
    });
 jQuery('.heart', this).click(function() {
     jQuery('.love1', this).attr('src', 'images/love1.jpg');
     jQuery('.love2', this).attr('src', 'images/love2.jpg');
     jQuery('.love3', this).attr('src', 'images/love3.jpg');
        return false;
    });
  });

但似乎什么也没做。我点击 "this" 一定是我错了,但我试着把它取下来,也没有任何改变。它必须永远这样做,我的意思是,如果客户点击每个按钮图像一千次,图像就会改变。

有什么帮助吗?谢谢

在这个问题中我们需要识别点击盘子或心脏的用户。所以我们需要找到触发点击事件的div块,然后我们可以更改特定div的love1,love2,love3的图像。我使用了以下代码,它工作正常。

jQuery(document).ready(function() {     
    jQuery('.plate', this).click(function() {
      jQuery(this).parent().find('.love1').attr('src', 'images/food1.jpg');
      jQuery(this).parent().find('.love2').attr('src', 'images/food2.jpg');
      jQuery(this).parent().find('.love3').attr('src', 'images/food3.jpg');
      return false;
    });
    jQuery('.heart', this).click(function() {
      jQuery(this).parent().find('.love1').attr('src', 'images/love1.jpg');
      jQuery(this).parent().find('.love2').attr('src', 'images/love2.jpg');
      jQuery(this).parent().find('.love3').attr('src', 'images/love3.jpg');
      return false;
    });
  });

Vareen 的回答很有道理。但是,我会这样清理它:

jQuery 实际上可以用美元符号 $ 表示,你不应该为每一行调用父级,只需将它分配给一个变量即可。此外,您的点击功能中不再需要 this,如下所示:

$(document).ready(function() {  

    $('.plate').click(function() {
        var $p = $(this).parent(); 
        $p.find('.love1').attr('src', 'images/food1.jpg');
        $p.find('.love2').attr('src', 'images/food2.jpg');
        $p.find('.love3').attr('src', 'images/food3.jpg');
        return false;
    });

    $('.heart').click(function() {
        var $p = $(this).parent(); 
        $p.find('.love1').attr('src', 'images/love1.jpg');
        $p.find('.love2').attr('src', 'images/love2.jpg');
        $p.find('.love3').attr('src', 'images/love3.jpg');
        return false;
    });

});