我正在從我的資料庫中提取檔案名串列并使用 jquery 動態列出它們。它們作為無序串列添加到 html 中。我希望每個專案都鏈接到我的詳細資訊頁面,但我還需要在單擊時將檔案 ID 保存到本地存盤中。這可能嗎?我只需要處理我的語法嗎?任何幫助表示贊賞。
jQuery函式:
$(function() {
var $files = $('#files');
$.ajax({
type: "GET",
url: 'some url',
data: {},
success: function(files) {
$.each(files, function(i, file){
$files.append('<a href="details.html" onclick="localStorage.setItem("file", file.id )";>' file.id '</a>');
});
},
// Error handling
error: function (error) {
console.log(`Error ${error}`);
}
});
})
HTML
<ul id="files"></ul>
uj5u.com熱心網友回復:
雙引號中有雙引號,還有一些隨機的“加號”。
將您的代碼更改為此,以使用模板文字代替:(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)
$files.append(`<a href="details.html" onclick="localStorage.setItem('file', '${file.id}')";>${file.id}</a>`);
使用字串模板將允許您直接將變數的值列印到字串中${variableName}
哎呀,我誤解了這個問題,留下這個答案關于如何在 localStorage 中快取串列以防有人需要它:
在從資料庫中提取之前,請查看它是否存在于本地存盤中:
$(function() {
let storedFiles = window.localStorage.getItem('stored_files');
if(storedFiles !== null) {
//found in local storage, use this:
files = JSON.parse(storedFiles); //local storage is stored as a string, you have to convert back to an object
//generate the list of files
generateListOfFiles(files);
} else {
// not found in local storage, get from database
$.ajax({
type: "GET",
url: 'some url',
data: {},
success: function(files) {
//generate the list of files:
generateListOfFiles(files);
// now store the files back in local storage for next time!
window.localStorage.setItem("stored_files", JSON.stringify(files)); // local storage should be stored as a string, as mentioned above
},
// Error handling
error: function (error) {
console.log(`Error ${error}`);
}
});
}
function generateListOfFiles(files) {
$.each(files, function(i, file){
let $files = $('#files');
$files.append('<a href="details.html" onclick="localStorage.setItem("file", file.id )";>' file.id '</a>');
});
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/461026.html
標籤:javascript html jQuery 阿贾克斯
上一篇:如何將Ajax(Jquery)轉換為fetchasync
下一篇:控制器回傳檔案但下載未開始
