2016-05-17 16 views
1

Können Sie mir helfen, ein kleines Problem zu lösen?Schaltfläche zum neuen Element hinzufügen

Ich habe einige Zahlen. Nach dem Klick wird die ausgewählte Figur in ein anderes div (basket) kopiert. Im Warenkorb sollte neue Schaltfläche erscheinen. Aber in meiner Lösung erschien dieser Buttom nach jedem Klick wieder. Wie kann ich das beheben? Dank und sorry für mein Englisch

Dieser Code

<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 Code

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

Hier Geige https://jsfiddle.net/fhxx9hm3/

+0

Sie benötigen [diese] (https://jsfiddle.net/8rs7zu5x/) – Satpal

+0

Haben Sie nur die Taste einmal angehängt werden soll? Wenn ja, könnten Sie JQuerys '.one()' verwenden (es ist wie '.on()', wird aber nur einmal pro Element ausgeführt) – DBS

Antwort

1

Sie auf die Schaltfläche pro Produkt nur einmal hinzufügen sollten.

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

Danke !! Es hat mir sehr geholfen! – Hlushenok

Verwandte Themen