2016-10-05 61 views
1

我使用fabric js並嘗試刪除組的父項時嘗試刪除組項目。以下是我的代碼。javascript從具有唯一屬性的畫布中刪除多個對象

jQuery(document).on('click', ".deleteBtn", function() { 
    if (canvas.getActiveObject()) { 
     var product_id = canvas.getActiveObject().get('product_id'); 
    } 
     var canvasObj = canvas.getObjects(); 

    for(var i = 0; i < canvasObj.length; i++){ 

     var objRef = canvasObj[i]; 

     var accessoryId = objRef.get('accessory_product_id'); 

     var product_type = objRef.get('product_type'); 

     if(accessoryId == product_id && product_type == "accessory"){ 
      canvas.remove(objRef); 
     } 

    } 
}); 

代碼是實際工作,但不能與作爲活動對象試圖刪除等兩個項目被正確去除相同accessoryIdproduct_type父項刪除所有項目。只有兩件物品留在畫布上。組中有5個項目。那些是圖像。我無法找到問題,請幫助。謝謝!

HTML代碼

<div id="content-tab-3" class="visualiser-product-category content-tab active"> 
    <ul> 
     <li> 
      <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter_Spice.png" class="visualizer-product-img" alt="Placeholder" data-quantity="1" data-product_type="parent" data-product_id="343"> 
       <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter-Spice-Desk-Floral.jpg" class="hide accessory-343"> 
       <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter-Spice-Garland.jpg" class="hide accessory-343"> 
       <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter-Spice-Tabletop.jpg" class="hide accessory-343"> 
       <img src="http://localhost/green_live/wp-content/uploads/2016/07/Winter-Spice-Wreath.jpg" class="hide accessory-343"> 
     </li> 
    </ul> 
</div> 
+0

請添加html標記 – Ted

+0

。它不是那麼重要的問題的HTML標記,但正如你問。我想在這裏發生的是,當使用點擊'data-product_type =「parent」中的刪除按鈕時,所有其他圖像都需要從畫布上移除。謝謝 – Dhananjaya

+0

我指的是畫布,而不是隨機的HTML頁面! – Ted

回答

0

你好,我注意到您的代碼,您試圖獲取活動的對象ID,但無論是否有活動的對象是不是您繼續循環,刪除對象 !! 也許,這會導致問題。

我要展示的例子與的forEach()函數,但繼續刪除對象只有在有活動對象

jQuery(document).on('click', ".deleteBtn", function() { 

    //only if there is active object, do i delete objects 
    if (canvas.getActiveObject()) { 
     //get productId of active object 
     var product_id = canvas.getActiveObject().product_id; 

     //loop on the canvas objects 
     canvas.getObjects().forEach(function (object) { 

       if(object.accessoryId == product_id && object.product_type == "accessory"){ 
       canvas.remove(object); 
       } 
     });//end forEach 
    }//end if 
});//end 'click' 

希望有所幫助,祝你好運。

相關問題