简体   繁体   English

如果单击 div 但从其他元素中删除相同的元素,如何添加元素?

[英]How to add an element if a div is clicked but remove the same element from the others?

I have an onclick function that add an element if a div is clicked我有一个 onclick function 如果单击 div 则添加一个元素

function clickOnADivToCreateLi(element) {
  var div = $(element);
  var i = document.createElement("i");
  $(i).addClass("fas fa-check-circle clicked");
  div.append(i);
}

But when I click on another div with the same class, I have two div with the same <i> and if I click again that div will have 2 <i> s但是当我单击另一个具有相同 class 的 div 时,我有两个具有相同<i>的 div,如果我再次单击该 div 将有 2 个<i>

How do add the <i> but at the same time remove it from the others?如何添加<i>但同时将其从其他人中删除?

Select the i elements matching the classes you assigned to it and call remove() before creating the new instance. Select 与您分配给它的类匹配的i元素并在创建新实例之前调用remove()

Also note that your code can be made much more succinct:另请注意,您的代码可以更简洁:

function clickOnADivToCreateLi(element) {
  $('i.fas.fa-check-circle.clicked').remove();
  $(element).append('<i class="fas fa-check-circle clicked" />');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM