我的應用程序按預期工作,直到我添加了存儲在localStorage中的項目的「DELETE」方法。停止替換localStorage中已存在的鍵和值的jQuery
我有這樣的HTML代碼,需要一個字符串:
<div>
<div ><input type="text" id="manuallyName" name="manuallyName" placeholder="Medicine Name, Strength & Form..." /></div>
<div class="ui-grid-a" style="padding:15px;">
<div class="ui-block-a"><input id="manualClear" type="Button" data-icon="delete" data-iconpos="left" value="Cancel" /></div>
<div class="ui-block-b"><input id="manuallyAdd" type="button" data-icon="cross" value="Add" /></div>
</div>
</div>
當「添加」按鈕被按下下面的腳本被稱爲:
$(document).ready(function() {
$('#manuallyAdd').click(function() {
if ($("#manuallyName").val() != "") {
var length = storage.length;
var number = storage.length;
if (length >= number) {
number++;
var key = "Medicine" + number.toString();
var value = $("#manuallyName").val();
storage.setItem(key, value);
}
document.getElementById("manuallyName").value = "";
return true;
}
else {
alert('Please Provide Medicine Name')
return false;
}
})
});
這個腳本工作正常,它基本上根據存儲大小檢查存儲長度並生成密鑰,並將textfield
內容添加到該值中並存儲它。
保存的項目然後通過另一個腳本顯示在listview
與id="medList"
中。 (我不會添加腳本來節省空間,但如果需要請評論,我會添加它)。
下面的腳本是一個需要從兩個listview
和localStorage
刪除項目的護理:
$('ul').on('click', '.del', function (el) {
$(this).closest('li').remove();
var key = $(this).attr('key');
localStorage.removeItem(key);
$('ul.medList').listview('refresh');
});
它需要一個儲存在listview
並相應刪除它的「鑰匙」。
現在,當一個項目從localStorage
按鍵變得不一致而當$('#manuallyAdd').click(function()
被再次調用,它將什麼都算,如果類似的鍵已經存在,它將取代它(和可悲的我沒有刪除我的問題依賴需要它)。
讓我解釋,例如:
我有以下的存儲:
Key = Medicine1 - Value = a
Key = Medicine2 - Value = b
Key = Medicine3 - Value = c
在上述Medicine2
的列表視圖被刪除,只留下Medicine1
和Medicine3
。
當我嘗試添加另一個「醫學」時,我期望Key = Medicine4 - Value = New Medicine
出現,但它會被存儲在Medicine3
擺脫舊的價值和存儲新的價值。
我相信這是由於我已經有了if statement
,而且我似乎沒有找到或解決一個不同的方法,這將爲我提供正確的解決方案。
我已經嘗試添加一個語句,檢查密鑰是否已經存在並提供了一個不同的鍵,但這隻能工作,直到另一個項目從列表中刪除。
任何指針或想法將不勝感激。
對不起,但我盡力解釋它。如果還有什麼不清楚的地方,請告訴我。
聽起來像是你需要一個對象或數組存儲'Medicine'數據。 [看到這個問題](http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage)。 – Blazemonger