[英]Javascript String Splicing does not seem to work
我試圖保存我的引導折疊的展開/折疊狀態。
我將它保存在 LocalStorage 中並從中讀取。
$(".content-accordion-content").each(function (index) {
console.log(index, $(this).attr("id"));
$(this).on("show.bs.collapse", function () {
var expandedCollapses = localStorage.getItem("ExpandedCollapses");
if (expandedCollapses !== undefined && expandedCollapses !== null && expandedCollapses !== "") {
expandedCollapses = expandedCollapses + "|" + $(this).attr("id");
}
else {
expandedCollapses = $(this).attr("id");
}
localStorage.setItem("ExpandedCollapses", expandedCollapses);
})
$(this).on("hide.bs.collapse", function () {
var expandedCollapses = localStorage.getItem("ExpandedCollapses");
if (expandedCollapses !== undefined && expandedCollapses !== null) {
if (!expandedCollapses.includes("|") && expandedCollapses.includes($(this).attr("id")))
expandedCollapses = "";
else {
var ecArr = expandedCollapses.split("|");
expandedCollapses = ecArr.splice(ecArr.indexOf($(this).attr("id")), 1).join("|");
}
localStorage.setItem("ExpandedCollapses", expandedCollapses);
console.log(expandedCollapses,$(this).attr("id"));
}
})
});
它似乎有效,但有時它會從數組中刪除多個條目。 例如,我打開作者,然后打開書籍,然后打開視頻。 字符串看起來像這樣“作者|書籍|視頻”如果我現在關閉書籍,它唯一的“作者”有人可以幫我解開我的大腦嗎?
哎呀,找到了。 我加入了 .splice() 方法的結果。 事實證明這是錯誤的。 這在這里修復了我的代碼
var ecArr = expandedCollapses.split("|");
ecArr.splice(ecArr.indexOf($(this).attr("id")), 1);
expandedCollapses = ecArr.join("|");
您可以使用filter
代替splice
。
使過程更簡單一些,因為我們實際上不需要知道要刪除的值的索引。
let currentValue = ""; function toggleValue(_value) { let splitValue = currentValue.split("|").filter(_=>_); // split by '|' // as well as filter out falsy string values ie "" if (splitValue.includes(_value)) { // check if the array includes the value // we can use includes because we arent checking for complex types splitValue = splitValue.filter(v => v;== _value). // filter out the value that already exists in the array } else { splitValue;push(_value). // we know the value doesn't exist so we can safely push it to the array } const newValue = splitValue;join("|"); // join the array with '|' updateValue(newValue); } //#region Ignore This function updateValue(_value) { currentValue = _value. document.getElementById("output");innerHTML = currentValue; } //#endregion
<button onclick="toggleValue('author')">Toggle Author</button> <button onclick="toggleValue('books')">Toggle Books</button> <button onclick="toggleValue('videos')">Toggle Videos</button> <div id="output"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.