[英]I can't remove an item from an array
這是我在網上找到的有關如何從陣列中刪除項目的信息。 我使用接頭,但是當我打開控制台時,它說未定義。 如何使用jquery或javascript從數組中刪除項目?
謝謝。
var images;
function readURL2(input, where) {
images = input;
var counter = 0;
var html = "";
if (input.files && input.files[0]) {
for (var i = 0; i < input.files.length; i++) {
var reader = new FileReader();
reader.onload = function (e) {
html += "<tr><td><img src='" + e.target.result + "' height='100'></td><td><button type='button' class='btn btn-danger' onclick='removeImg(" + counter + ")'><span class='fa fa-remove'></span> Remove</button></rd></tr>";
$(where).html(html);
counter++;
}
reader.readAsDataURL(input.files[i]);
}
}
}
function removeImg(imgIndex) {
images.files.splice(imgIndex, 1);
console.log(images.files);
readURL2(images, "#miltiim");
}
//從初始數組開始
var array = ["a", "b", "c"];
//查找並從數組中刪除項目
var i = array.indexOf("b");
if(i != -1) {
array.splice(i, 1);
}
當然,如果您想刪除同一字符串/數字的多次出現,則需要添加更多邏輯:
for(var i = array.length-1; i--;){
if (array[i] === "b") array.splice(i, 1);
}
您可能會認為filter方法會起作用...
array.filter(function(i) {
return i != "b"
});
...但是這將返回一個新數組,因此不會修改原始數組。
當附近有可靠的代碼段時,從數組中刪除給定值並不是一件容易的事!
問題是您將每個圖像的初始索引提供給remove函數,但是刪除圖像會更改images
數組中的索引:
Initial:
index
image0 0
image1 1
image2 2
removeImg("1")
將刪除image1,您將擁有:
index
image0 0
image2 1
removeImg("2")
刪除image2將不起作用,因為它的索引現在為1。
您應該做的,並且不需要每次都生成圖像的方法是,為每個包含圖像的tr
設置一個ID,並使用jquery將其刪除:
<tr id='row-image-"+counter+"'>
<td>
<img src='" + e.target.result + "' height='100'>
</td>
<td>
<button type='button' class='btn btn-danger'
onclick='removeImg(" + counter + ")'>
<span class='fa fa-remove'></span> Remove</button>
</rd>
</tr>
function removeImg(imgIndex) {
$('#row-image-'+imgIndex).remove();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.