正如您所看到的,如果您尝试了代码并在应用程序中保存输入,它将按从上到下的顺序保存,我希望它是从下到上的顺序,这是整个代码,如果您想要html和css代码我会给你
let myLeads = []
const inputEl = document.getElementById("input-el")
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")
const deleteBtn = document.getElementById("delete-btn")
const leadsFromLocalStorage = JSON.parse( localStorage.getItem("myLeads") )
const tabBtn = document.getElementById("tab-btn")
if (leadsFromLocalStorage) {
myLeads = leadsFromLocalStorage
render(myLeads)
}
tabBtn.addEventListener("click", function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
myLeads.push(tabs[0].url)
localStorage.setItem("myLeads", JSON.stringify(myLeads) )
render(myLeads)
})
})
function render(leads) {
let listItems = ""
for (let i = 0; i < leads.length; i++) {
listItems += `
<li>
<a target='_blank' href='${leads[i]}'>
${leads[i]}
</a>
</li>
`
}
ulEl.innerHTML = listItems
}
deleteBtn.addEventListener("dblclick", function() {
localStorage.clear()
myLeads = []
render(myLeads)
})
inputBtn.addEventListener("click", function() {
myLeads.push(inputEl.value)
inputEl.value = ""
localStorage.setItem("myLeads", JSON.stringify(myLeads) )
render(myLeads)
})
我尝试颠倒渲染函数中的顺序,但它没有按预期工作。
您只需将
.push()
更改为 .unshift()
。
这里部分工作(本地存储在代码片段中被禁用,因此我将其与扩展上下文功能一起评论):
let myLeads = []
const inputEl = document.getElementById("input-el")
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")
const deleteBtn = document.getElementById("delete-btn")
const leadsFromLocalStorage = []; //JSON.parse( localStorage.getItem("myLeads") )
const tabBtn = document.getElementById("tab-btn")
if (leadsFromLocalStorage) {
myLeads = leadsFromLocalStorage
render(myLeads)
}
tabBtn.addEventListener("click", function(){
//chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
// EDIT:
myLeads.unshift(tabs[0].url)
// localStorage.setItem("myLeads", JSON.stringify(myLeads) )
render(myLeads)
//})
})
function render(leads) {
let listItems = ""
for (let i = 0; i < leads.length; i++) {
listItems += `
<li>
<a target='_blank' href='${leads[i]}'>
${leads[i]}
</a>
</li>
`
}
ulEl.innerHTML = listItems
}
deleteBtn.addEventListener("dblclick", function() {
// localStorage.clear()
myLeads = []
render(myLeads)
})
inputBtn.addEventListener("click", function() {
// EDIT:
myLeads.unshift(inputEl.value)
inputEl.value = ""
// localStorage.setItem("myLeads", JSON.stringify(myLeads) )
render(myLeads)
})
<input type="text" id="input-el">
<button id="input-btn">SAVE INPUT</button>
<button id="tab-btn">SAVE TAB</button>
<button id="delete-btn">DELETE ALL</button>
<ul id="ul-el"></ul>