jQuery 选择一个方块并将其背景颜色更改为列表中其中一个方块的背景颜色

jQuery pick a block and change it's bg color with the bg color of one of the blocks from list

例如,在一列中我有 3 个块 (div),在第二列中我有其他块的列表 (div)。

第一列块代表蛋糕层,第二列块代表可以应用于任何蛋糕层的口味。

因此,通过选择一个楼层,我想为这个特定楼层选择一种口味,然后,通过选择另一层,我想应用其他口味中的一种...

类似的东西:

带有每个口味标题的示例,但实际上并不能正常工作,因为此后口味适用于之前选择的楼层。

$(".cake-floor").click(function(){
  var floor = $(this);
  $(".cake-taste").click(function(){
    var taste = $(this).text();
    $(floor).text(taste);
  });
});

HTML:

<div class="col-md-6 mb-sm-3">
  <div style="background: #dedede; height: 40px; width: 40px; border-radius: 50%; margin-bottom: -10px;"></div>
  <div class="cake-floor mb-2" data-floor="3"></div>
  <div class="cake-floor mb-2" data-floor="2"></div>
  <div class="cake-floor" data-floor="1"></div>
</div>

<div class="col-md-6 tastes">
  <div class="cake-taste text-center" data-taste="chocolate">chocolate</div>
  <div class="cake-taste text-center" data-taste="caramel">caramel</div>
  <div class="cake-taste text-center" data-taste="banana">banana</div>
  <div class="cake-taste text-center" data-taste="lime">lime</div>
  <div class="cake-taste text-center" data-taste="blueberry">blueberry</div>
  <div class="cake-taste text-center" data-taste="rapsberry">rapsberry</div>
  <div class="cake-taste text-center" data-taste="strawberry">strawberry</div>
</div>

只需将您的代码更改为:

$(".cake-floor").click(function(){
  var floor = $(this);
  $(".cake-taste").off().click(function(){
    var taste = $(this).text();
    floor.text(taste);
  });
});

第一次选择 div.cake-floor 时 - 它会向 $(".cake-taste").click 事件添加一个事件侦听器。

当再次选择任何 div.cake-floor 时,将添加一个新事件。现在有两种侦听事件的方法,因此多个 div 正在更新。

这可以使用 jQueryoff 事件解决。

$(".cake-taste").off().click(function(){
 ...
}

参考jsFiddle here