在我的網站中,我列出了用戶可以分享他們對它們的評論的電影和電視劇。用戶可以添加評論,但是在接收評論時,會回傳一個未定義的值。(我正在嘗試從movieComment 中獲取評論。movieComment 商店對電影的評論)
var show = qs["movieId"];
/* show variable is giving my movie's ID and it is 1 */
btnComment.addEventListener('click', (e) => {
var movieComment = document.getElementById('textComment').value;
push(child(firebaseRef, 'Movies/' show '/movieComment/'), movieComment) {
movieComment: movieComment
};
});
function AddItemsToTable2(comment) {
const comments = `
<td>Alan Smith</td>
<td><i style="color:rgb(91, 186, 7)"></i></td>
<td>${comment}<h6>[May 09, 2016]</h6></td>
`;
html = comments;
body2.innerHTML = html;
}
}
function AddAllItemsToTable2(TheComments) {
body2.innerHTML = "";
TheComments.forEach(element => {
AddItemsToTable2(element.movieComment);
});
}
function getAllDataOnce2() {
var show = qs["movieId"];
get(child(firebaseRef, 'Movies/' show '/movieComment')).then((snapshot) => {
var comments = [];
comments.push(snapshot.val());
console.log(comments);
AddAllItemsToTable2(comments);
});
}
window.onload = (event) => {
getAllDataOnce2();
};

Console.log(電影)

未定義的錯誤:

uj5u.com熱心網友回復:
專注于這個功能:
function AddAllItemsToTable2(TheComments) {
body2.innerHTML = "";
TheComments.forEach(element => {
AddItemsToTable2(element.movieComment);
});
}
TheComments這里的物件是Record<string, string>[]:
TheComments = [{
"-Mstwhft8fKP6-M2MRIk": "comment",
"-Mstwj5P2TD_stgvZL8V": "a comment",
"-MstwjxvmkNAvWFaIejp": "another comment"
}]
當你遍歷這個陣列時,你最終會得到一個沒有movieComment屬性的元素物件,這就是為什么當你把它提供給AddItemsToTable2你時得到undefined.
要解決此問題,您需要更改組裝TheComments物件的方式:
function AddAllItemsToTable2(TheComments) { // TheComments: ({id: string, text: string})[]
body2.innerHTML = "";
TheComments.forEach(commentObj => AddItemsToTable2(commentObj.text));
}
function getAllDataOnce2() {
const show = qs["movieId"];
get(child(firebaseRef, 'Movies/' show '/movieComment'))
.then((snapshot) => {
const comments = [];
snapshot.forEach(childSnapshot => {
comments.push({
id: childSnapshot.key, // store this for linking to database/anchors
text: childSnapshot.val()
});
});
console.log(comments);
AddAllItemsToTable2(comments);
});
}
另外一點,在使用innerHTML和使用innerText任何用戶生成的內容時要注意 XSS 風險。此外,您應該將評論內容包裝在表格行中,以便正確連接評論。
function AddItemsToTable2(commentObj) {
const commentEle = document.createElement('span');
commentEle.id = `comment_${commentObj.id}`;
commentEle.innerText = commentObj.text;
const commentRowHTML = `
<tr>
<td>Alan Smith</td>
<td><i style="color:rgb(91, 186, 7)"></i></td>
<td>${commentEle.outerHTML}<h6>[May 09, 2016]</h6></td>
</tr>`;
body2.innerHTML = commentRowHTML;
}
function AddAllItemsToTable2(TheComments) {
body2.innerHTML = "";
TheComments.forEach(commentObj => AddItemsToTable2(commentObj));
}
使用上面的代碼塊,您現在可以添加#comment_-MstwjxvmkNAvWFaIejp到當前頁面 URL 的末尾以鏈接到“另一個評論”評論,直接類似于 StackOverflow 鏈接到評論的方式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405728.html
標籤:
