[英]Removing Checked Items From Array
我有一個函數,它接受列表中所有未檢查的項目,並根據它們創建一個新數組。
// Allows user to remove keywords from the locaStorage
$('#clearChecked').click(function() {
currentArray = [];
$('.check').each(function() {
var $curr = $(this);
if (!$curr.is(':checked')) {
var value = $curr.parent().text();
currentArray.push(value);
localStorage.setItem('keyWords', JSON.stringify(currentArray));
loadKeyWords();
} else {
$curr.parent().remove();
}
});
});
問題是,如果我檢查所有項目,它將不會刪除任何項目。 或者,如果只剩一個項目,就不會讓我刪除最后一個項目。
但是,只要剩下一件物品,它就允許我刪除任意數量的物品。
如何更改我的功能,以允許我刪除數組中的最后一項或所有被選中的項目。
我正在輸出這樣的數組,
// Generate random id for id of keywords
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
var x = guidGenerator();
$('#keyWords').prepend('<li class="list-group-item" data-style="button"><input id="'+ x +'" class="check" name="check" type="checkbox"><label for="'+ x +'">'+localArray[i]+'</label></li>');
在html文件中
<button id="clearChecked">Clear Checked Items</button>
<ul id="keyWords">
<li class="list-group-item" data-style="button">
<input id="4667ac55-5de4-df61-9b82-9b50c728adea" class="check" name="check" type="checkbox">
<label for="4667ac55-5de4-df61-9b82-9b50c728adea">qedfeqdeqdeq</label>
</li>
</ul>
只需在復選框單擊事件中添加代碼即可:
if($('.check:checked').length == $('.check').length) {
window.localStorage.clear();
location.reload();
return false;
}
我通過以下方法解決了這個問題(至少在我這邊):
ID
和標簽的for
更改for
不帶空格的唯一字符串 添加了});
到您發布的jQuery的下方,因為它沒有關閉主要的原始功能。
<button id="clearChecked">Clear Checked Items</button> <ul id="keyWords"> <li class="list-group-item" data-style="button"> <input id="link_0" class="check" name="check" type="checkbox"> <label for="link_0">I am a link</label> </li> <li class="list-group-item" data-style="button"> <input id="link_1" class="check" name="check" type="checkbox"> <label for="link_1">I am a link</label> </li> <li class="list-group-item" data-style="button"> <input id="link_2" class="check" name="check" type="checkbox"> <label for="link_2">I am a link</label> </li> </ul> $('#clearChecked').click(function() { currentArray = []; $('.check').each(function() { var $curr = $(this); if (!$curr.is(':checked')) { var value = $curr.parent().text(); currentArray.push(value); localStorage.setItem('keyWords', JSON.stringify(currentArray)); loadKeyWords(); } else { $curr.parent().remove(); } }); // only closing the $('.check').each(function() { function }); // closing the $('#clearChecked').click(function() { function
編輯:
關於您發布的GUID
...對其進行修復。
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.