2017-08-22 34 views
0

我正在基於這個例子一塊本地存儲功能:編輯本地存儲代碼的唯一ID添加到每個元素

https://scriptscodes.com/codes/CrocoDillon/pIlKB/preview/index.html

CSS:

/* https://scriptscodes.com/codes/CrocoDillon/pIlKB/preview/index.html */ 
.list li{ 
    cursor:pointer; 
} 

.list li:before,.list li.fav:before { 
    font-family: FontAwesome; 
    content:"\f08a"; 
    color:white; 
    margin-right:10px; 
    font-size:14px; 
} 

.list li:hover:before { 
    font-family: FontAwesome; 
    content:"\f004"; 
    color:white; 
    margin-right:10px; 
    font-size:14px; 
} 

.list li.fav:hover:before,.list li.fav:before { 
    font-family: FontAwesome; 
    content:"\f004"; 
    color:red; 
    margin-right:10px; 
    font-size:14px; 
} 

樣本HTML :

<div class="list" style="background:#ccc; padding:20px;"> 
    <ul class="list-unstyled"> 
     <li id="petty">petty</li> 
     <li id="bedfordshire">bedfordshire</li> 
     <li id="rearing">rearing</li> 
     <li id="jane">jane</li> 
     <li id="furore">furore</li>       
    </ul> 
</div> 

然後我可以添加每個項目到本地存儲與此:

JS:

var favorites = JSON.parse(localStorage.getItem('favorites')) || []; 

document.querySelector('.list').addEventListener('click', function(e) { 
    var id = e.target.id, 
     item = e.target, 
     index = favorites.indexOf(id); 
    if (!id) return; 
    if (index == -1) { 
     favorites.push(id); 
     item.className = 'fav'; 
    } else { 
     favorites.splice(index, 1); 
     item.className = ''; 
    } 
    localStorage.setItem('favorites', JSON.stringify(favorites)); 
}); 

使用此代碼測試頁面是在這裏:https://jimpix.co.uk/testing/test3.asp

因此, 「收藏夾」 陣列看起來像這樣:

favorites:"["petty","rearing","jane"]" 

我需要解決如何編輯JS以便每個元素都有一個唯一的ID,因此數組看起來像這樣:

favorites:"[{"id":"1","name":"petty"},{"id":"2","name":"rearing"},{"id":"3","name":"jane"}]" 

有沒有可能這樣做?

我不想使用jQuery,因爲我必須重寫此代碼中使用的JS,並且還要在另一個頁面上輸出本地存儲數據。

感謝

+0

我看不到這個問題,只需將'favorites.push({id:1,name:'petty「}'推入你的數組並對其進行字符串化處理?對於一個唯一的Id,可以使用for循環的索引或嘗試這樣的事情:'Math.floor(window.performance.now()* 1000)' –

+0

謝謝 - 工作。我還有一個問題 - 你可以看看我可以然後檢查數組,看看是否該項目/值存在於數組中,因爲每次單擊一個列表項時,現有的'index = favorites.indexOf(id);'行總是返回'-1' - 似乎將下一個插入到「name」元素/鍵中意味着indexOf找不到它? – 4532066

+0

我爲這兩個請求都寫了一個答案 –

回答

2

我看不到的問題只是把favorites.push({ id: 1, name: "petty" }到您的陣列事後字符串化呢?對於一個唯一的ID取的該指數環或嘗試這樣的事:Math.floor(window.performance.now() * 1000)

爲了找到一個元素是否在數組中只要做到以下幾點:

function isIdInArray(id) { // param id is the id youre looking for in the array 
    var isInArray = false; 
    favorites.forEach(function(favorite){ 
     if(favorite.id === id){ 
      isInArray = true; 
     } 
    }); 
    return isInArray; 
} 

爲了澄清,如果你讓index = favorites.indexOf(id);這將尋找一個字符串的字符串。例如, "apple".indexOf("ple");將返回2,因爲它在位置2的字符串中找到「ple」。如果字符串不包含搜索的字符串,例如:"apple.indexOf("tomato");返回值將是-1。你不能在數組上執行indexOf。您可以用indexOf()搜索您的字符串數組索引值,但我不建議您這樣做。

相關問題