你能帮我解决一个小问题吗?
我有一些数字。单击后,将选定的图形复制到另一个 div(篮子)。 在篮子里应该出现新的按钮。但在我的解决方案中,每次点击后这个按钮都会再次出现。 我该如何解决这个问题? 谢谢,对不起我的英语
这段代码
<div class="products__list__items">
<div class="products__list__item row">
<figure class="product first" data-class="first">
<img src="https://www.tineye.com/images/robot-search-header.png" alt="product1" class="product__img">
<figcaption class="product__title">One</figcaption>
</figure>
</div>
<div class="products__list__item row">
<figure class="product first" data-class="first">
<img src="https://www.tineye.com/images/robot-search-header.png" alt="product1" class="product__img">
<figcaption class="product__title">Two</figcaption>
</figure>
</div>
<div class="products__list__item row">
<figure class="product first" data-class="first">
<img src="https://www.tineye.com/images/robot-search-header.png" alt="product1" class="product__img">
<figcaption class="product__title">Three</figcaption>
</figure>
</div>
</div>
<div class="basket">
</div>
J查询代码
$(document).ready(function() {
var addToBasket = function() {
var that = $(this);
if(!that.hasClass('added')) {
that.clone().appendTo($('.basket'));
that.addClass('added');
};
$('.basket .product').append('<button>x</button>');
};
$(document).on("click",".products__list__item .product",addToBasket);
});
这里 fiddle https://jsfiddle.net/fhxx9hm3/
最佳答案
您应该只为每个产品添加一次按钮。
var addToBasket = function() {
var that = $(this);
if(!that.hasClass('added')) {
//Append the button here
that.clone().add('<button>x</button>').appendTo($('.basket'));
//Or
//that.clone().append('<button>x</button>').appendTo($('.basket'));
that.addClass('added');
};
//Following statement is not required
//$('.basket .product').append('<button>x</button>');
};
关于javascript - 将按钮添加到新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37276752/