我想只删除类型为textbox
的对象,但在使用for循环时,不删除all可能是因为对象长度更改和索引移位。有什么建议吗?
这是我的代码
texBoxItems = canvas.getObjects();
for(var i=0; i<texBoxItems.length; i++ ){
if(texBoxItems[i].get('type') == "textbox"){
if(texBoxItems[i].active == false){
canvas.setActiveObject(texBoxItems[i]);
canvas.remove(texBoxItems[i]);
}
else{
canvas.remove(texBoxItems[i]);
}
}
}
答案 0 :(得分:1)
var objects = canvas.getObjects('textbox');
canvas.remove(...objects);
获取getObjects('textbox')类型的所有对象,然后使用remove()删除对象。
<强> 样本 强>
var canvas = new fabric.Canvas('c');
var text1 = new fabric.Textbox('Text',{
left:10,top:20
})
var text2 = new fabric.Textbox('Text',{
left:50,top:50
})
var rect = new fabric.Rect({
left:150,top:150,width:100,height:100
})
canvas.add(text1,text2,rect);
function remove(){
var objects = canvas.getObjects('textbox');
canvas.remove(...objects);
}
canvas{
border:1px solid #000;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<button id="aligntext" onclick="remove()">remove</button>
<canvas id="c" width="400" height="400" style="border:1px solid #000000;"></canvas>
答案 1 :(得分:1)
另一种方法是从对象的长度(减一)开始直到零:
<script>
function what_i_do(that) {
initid++;
var objTo = document.getElementById('what_i_do');
var divtest = document.createElement("tr");
divtest.setAttribute("class", "removeclass" + initid);
divtest.setAttribute("id", "removeclass" + initid);
var rdiv = 'removeclass' + initid;
divtest.innerHTML = '<td><input type="text" name="item_no[]"></td><td colspan="3"> <table> <tr> <td><input type="text" class="smlbox" name="part_no[]" onblur="checkavailpart(this)"></td><td><input type="number" class="smlbox" name="qty[]"></td><td> <input type="number" class="smlbox price_quotd_cls" name="price_quotd[]"> </td></tr><tr> <td colspan="3"><input type="text" class="smlbox2" name="part_desc[]"></td></tr></table> </td><td><input type="text" name="part_note[]"></td><td><input type="text" name="part_internal_note[]"></td><td><input type="text" class="datepicker" name="pc_rfq_date[]"></td><td><input type="text" name="pc_rfq_cus_no[]"></td><td><input type="text" name="pc_rfq_price[]"></td><td><input type="text" class="datepicker" name="pc_po_date[]"></td><td><input type="text" name="pc_po_cus_no[]"></td><td><input type="text" name="pc_po_price[]"></td><td><input type="text" class="datepicker" name="pv_po_date[]"></td><td><input type="text" name="pv_po_cus_no[]"></td><td><input type="text" name="pv_po_price[]"></td><td><input type="text" name="mu_per[]" onblur="calculate_quote_rate(this)"></td><td><i class="fa fa-times-circle fa-2x" style="color:red" onclick="remove_education_fields(' + initid + ');"></i></td>';
objTo.appendChild(divtest);
}
</script>