gpt4 book ai didi

javascript - 如何在 JavaScript 中从本地存储加载到行时使按钮起作用

转载 作者:行者123 更新时间:2023-11-28 07:41:49 25 4
gpt4 key购买 nike

//loops through all rows and cells and saves them into local storage as objects
window.onbeforeunload = function() {
var rows = document.getElementById('firsttable').tBodies[0].rows;
for (var i = 0; i < rows.length; i += 1) {
localStorage.setItem(i, JSON.stringify({
Item: rows[i].cells[0].innerHTML,
filling1: rows[i].cells[1].innerHTML,
filling2: rows[i].cells[2].innerHTML,
filling3: rows[i].cells[3].innerHTML,
Stock: rows[i].cells[4].innerHTML,
min: rows[i].cells[5].innerHTML,
sold: rows[i].cells[6].innerHTML,
closeAcc: rows[i].cells[7].innerHTML,
sell: rows[i].cells[8].innerHTML,
dltButton: rows[i].cells[9].innerHTML
}));
};
};


//loads the objects into rows with the values in their cells
window.onload = function() {
var r = 0,
c = 0;
//load the actual data from localstorage into html rows
for (x in localStorage) {
var row = table.insertRow(r),
obj = JSON.parse(localStorage.getItem(x));
for (i in obj) {
var cell = row.insertCell(c);
cell.innerHTML = obj[i];
c += 1
}
r += 1;
c = 0;
}
};


//where the problem is
$(function() {
$('table td').click(function(e) {
if (e.target.id === "Sellbtn") {
var sell = prompt("Enter the amount");
for (var i = 0; i < table.length; i += 1) {};
this.parentNode.parentNode.cells[4].innerHTML = parseInt(this.parentNode.parentNode.cells[4].innerHTML) - sell; //not working and no when put inside the for loop it doesn't work idk why
} else if (e.target.id === "Deletebtn") {
return false;
} else {
var ask = prompt("Input");
$(this).html(ask);
}
});
});

因此,我插入一行并将详细信息添加到单元格中,然后如代码片段中所述,当用户关闭浏览器然后加载时,第一个函数将可用的行和单元格保存到本地存储中的 JSON 字符串化对象中它们在加载期间出现,问题在于按钮 idk 如何使它们在加载后发挥作用(用户关闭并再次打开)。因此,想象一下,您的 HTML 表格包含几行及其单元格,每行都有两个按钮(出售和删除),当用户再次打开应用程序时,如何使它们发挥作用?顺便说一句,这些按钮都是在最初添加行时使用 createElement() 动态添加的

最佳答案

尝试委托(delegate)表格行上的点击事件,因为它们是在 DOM 加载后创建的:

$('table').on("click", "td", function(e) {

关于javascript - 如何在 JavaScript 中从本地存储加载到行时使按钮起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27935944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com