在小提琴中,我創建了一個按鈕,將新對象添加到文檔和數組。 單擊每個對象將其從文檔中刪除。我怎樣才能將它從數組中移除?從數組中刪除動態對象從DOM中刪除
<button id="btn">addBox</button>
<p style="font-size: 12px">click boxes to remove</p>
<p id="p2" style="font-size: 12px"></p>
<script>
$(document).ready(function() {
boxes = []
boxNumber = 0
function Box() {
this.output = $("<div />").addClass('box').attr('id', "box" + boxNumber++).appendTo("body");
boxes.push(this);
}
function addBox() {
var box = new Box();
$('.box').each(function() {
var boxID = $(this).attr('id');
$(this).text(boxID);
});
$('#p2').text(boxes);
}
function removeBox() {
$(this).remove();
}
$('body').on('click', '.box', function() {
$(this).remove();
});
$('#btn').click(addBox);
});
</script>
看:[Array.prototype.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)和[Array.prototype .indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) – Givi
在數組中找到DOM元素,使用.splice()刪除一個項目來自陣列。但是,有人可能會問爲什麼你甚至有數組,當你可以隨時用DOM查詢生成數組。 – jfriend00