【问题标题】:Is it possible to change the clone and the original element at the same time? - jQuery是否可以同时更改克隆和原始元素? - jQuery
【发布时间】:2024-01-01 12:33:02
【问题描述】:

我在 div 父级中有一个带有克隆的元素。我想点击 clone 并更改此克隆及其原始元素的 css。但同时,如果一开始我点击 original 元素,我想更改原始元素及其克隆。

有可能吗?

HTML

<div id="parent">
  <div class="hello">
  Hello
  </div>
</div>

CSS

.hello {
  width: 100px;
  height: 100px;
  color: #fff;
  background-color: #000;
  margin: 10px;
}

JAVASCRIPT

$('.hello').clone().appendTo('#parent');
$('.hello').on('click',function(){
    $(this).css('background-color','red');
});

这里是jsfiddle:https://jsfiddle.net/vcyLkdas/

$('.hello').clone().appendTo('#parent');

$('.hello').on('click',function(){
	$(this).css('background-color','red');
});
.hello {
  width: 100px;
  height: 100px;
  color: #fff;
  background-color: #000;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<div class="hello">
Ciao
</div>
</div>

【问题讨论】:

  • this改成'.hello'能用吗?

标签: javascript jquery html css clone


【解决方案1】:

在您的处理程序中将$(this) 替换为$(".hello")

$(".hello").clone().appendTo("#parent");

$(".hello").on("click", function () {
  $(".hello").css("background-color", "red");
});
.hello {
  width: 100px;
  height: 100px;
  color: #fff;
  background-color: #000;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="parent">
  <div class="hello">
    Ciao
  </div>
</div>

【讨论】:

    【解决方案2】:

    在 jQuery 点击事件中,“this”仅指被点击的元素,而不是 .hello 类的所有元素。因此,您需要将“this”更改为“.hello”:

    $('.hello').on('click',function(){
        $('.hello').css('background-color','red');
    });
    

    【讨论】: