将按钮添加到新元素中

Add button to new element

本文关键字:元素 新元素 按钮 添加      更新时间:2023-09-26

你能帮我解决一个小问题吗?

我有一些数字。点击后,将选中的图形复制到另一个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>

Jquery代码

$(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);
});

这是小提琴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>');       
};

演示