3 回答

TA貢獻1876條經驗 獲得超5個贊
存儲函數名稱并從其他腳本中讀取它以調用該函數。另一個腳本必須包含該函數。
如果您在第一個腳本中根本不使用它,則將其包含在兩個腳本中或僅包含在第二個腳本中。
const obj = {
payment: () => {
var name = document.getElementByID('name').value
alert(name)
}
}
第一個腳本(設置要存儲的函數名稱)
localStorage.setItem('func', 'payment')
第二個腳本(獲取函數名稱并調用它)
const funcName = localStorage.getItem('func')
// Call function
obj[funcName]()
注意:如果您不想復制代碼,則使用 eval() 是解決方案,但我認為這非常危險,因為用戶可以修改 localStorage 中的函數并執行任何代碼。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

TA貢獻1776條經驗 獲得超12個贊
FAIK,localStorage 不能存儲函數。但是,您可以存儲代碼并稍后對其進行評估。
function Payment() {
var name = document.getElementByID("name").value;
alert(name);
}
// store Payment or Payment.toString()
// storing Payment() is storing the function's result
localStorage.setItem("Payment", Payment.toString())
然后以后...
const StoredPayment = eval('(' + localStorage.getItem("Payment") + ')');
StoredPayment();

TA貢獻1798條經驗 獲得超3個贊
您可以將函數存儲為stringintolocalStorage并可以使用函數重用它eval。
將函數存儲到localStorage
function Payment() {
var name = document.getElementById("name").value;
console.log(name);
alert(name);
}
localStorage.setItem('func', Payment.toString());
從 localStorage 獲取函數日期。
localStorage.getItem('func');
附件顯示了如何調用字符串化函數。
var payment = `function Payment() {
var name = document.getElementById("name").value;
console.log(name);
alert(name);
}`;
eval(payment);
Payment();
<input type="text" id="name" value="hello" />
添加回答
舉報