2016-05-17 100 views
1

你能帮我解决一个小问题吗?将按钮添加到新元素

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

+0

你需要[这](https://jsfiddle.net/8rs7zu5x/) – Satpal

+0

你只需要一次追加按钮?如果是这样,你可以使用JQuery的'.one()'(就像'.on()',但每个元素只能执行一次) – DBS

回答

1

你应该每个产品只有一次添加的按钮。

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>');  
}; 

DEMO

+0

Thanks !!这对我帮助很大! – Hlushenok