错误 无法读取 null 的属性'innerHTML'。(JavaScript & Firebase)



我有一个配置文件页面,应该显示用户的信息。如果用户希望更改个人信息,他们必须单击名为编辑信息的按钮,该按钮将重定向到带有表单的页面。

问题是:我试图将表单信息放回主Dom profile.html的占位符中,这样用户就可以看到以前输入的内容。

但是,当要将firebase数据呈现到实时侦听器上,以便将firebase保存的数据插入profile.html时,我会收到一个错误。无法读取null的属性"innerHTML">

可能的问题:由于表单信息位于";name.html";试图针对";profile.html";导致无法读取null的属性"innerHTML"。

我使用的代码:

const name = document.querySelector('.switch_name');
// Render Name Data
const renderName = (data, id) => {
const html = `
<div>
<a href="#" data-id="${id}">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input type="text" class="validate" value="${data.name}"/>
<label>Full Name</label>
</div>
</a>
</div> `;
// -----REPLACE HTML----
name.innerHTML += html;
};
// Savng Profile Info To Database
const profileForm = document.querySelector('.profile-form');
const submitBtn = document.querySelector('.submit');
submitBtn.addEventListener('click', (e) => {
e.preventDefault();
const fullName = profileForm['icon_prefix'].value;
db.collection('profile').doc().set({
name: fullName,
}).then(() => {
window.location.href = "/pages/profile.html";
console.log('data saved');
}).catch(() => {
console.log(error);
});
});
// Real-Time Data
db.collection('profile').onSnapshot((snapshot) => {
snapshot.docChanges().forEach(change => {
if(change.type === 'added'){
renderName(change.doc.data(), change.doc.id);
}
if(change.type === 'removed'){
}
});
});
<div class="switch_name">
<a href="/pages/name.html">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input type="text" class="validate"/>
<label>Full Name</label>
</div>
</a>
</div>

我认为您误解了替换函数的使用。

代码name.replace(html, name);name中查找字符串html,然后用name替换该字符串的出现。请参阅此处了解如何使用替换

在您的情况下,您可能想将该行更改为name.innerHTML = html;

最新更新