我有這個代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./framework.js"></script>
</head>
<body>
<p f-text="name"></p>
<script>
Framework.store('name', 'Joe');
</script>
</body>
</html>
document.querySelectorAll('*').forEach((element) => {
if (element.hasAttribute('f-text')) {
const textValue = element.getAttribute('f-text');
element.innerHTML = window.fStore[textValue];
}
});
window.Framework = {
store: (key, value = '') => {
if (value === '') {
return window.fStore[key];
}
window.fStore[key] = value;
}
}
但是得到這個錯誤:
TypeError: Cannot set properties of undefined (setting 'name')
at Object.store (/framework.js:15:24)
at /:12:15
我希望頁面通過從 獲取鍵f-text,在 中找到鍵的值window.fStore,然后將 設定element.innerHTML為值來呈現“Joe” 。Framework.store()接受一個鍵和一個值,如果沒有值,它從鍵中回傳值window.fStore,如果有,則設定window.fStore[key]為該值。
uj5u.com熱心網友回復:
您需要先檢查是否window.fStore存在。
window.Framework = {
store: (key, value = '') => {
if(!window.fStore) window.fStore = {}
if (value === '') {
return window.fStore[key];
}
window.fStore[key] = value;
}
}
Framework.store('name', 'Joe');
document.querySelectorAll('*').forEach((element) => {
if (element.hasAttribute('f-text')) {
const textValue = element.getAttribute('f-text');
element.innerHTML = window.fStore[textValue];
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p f-text="name"></p>
</body>
</html>
uj5u.com熱心網友回復:
您可能還需要等到視窗首先加載。如果你不這樣做,有些瀏覽器會讓你頭疼
window.addEventListener('load', e=>{
window.Framework = {
store: (key, value = '') => {
if(!window.fStore)
window.fStore = {};
if (value === '')
return window.fStore[key];
window.fStore[key] = value;
}
}
Framework.store('name', 'Joe');
document.querySelectorAll('*').forEach((element) => {
if (element.hasAttribute('f-text'))
element.innerHTML = window.fStore[element.getAttribute('f-text')];
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363210.html
標籤:javascript html 不明确的 类型错误 核心价值
上一篇:谷歌地圖API確定縮放級別?
