【发布时间】:2018-01-11 19:46:56
【问题描述】:
我有一个元素数组(我将在下面显示一个 sn-p),具有不同级别的数组元素,我想要一个特定的函数来检索某个级别的数组元素并呈现它们在一个表中,我最初的两个函数可以无缝运行,但是在复制我以前的函数并更改适当的变量命名和引用后,第二个函数无法成功地将数组元素显示到屏幕上。
我一直在寻找可能的错误引用或轻微缺失的元素,但我不知所措。
这是我的 var 数组:
{title: "Basketball Topics", followers: 122, articles: 4, posts: [
{postId: 106, contents: "data", author: "data", replies:[
{replyId: 16, comment: "data", comment_author: "data"},
{replyId: 17, comment: "data", comment_author: "data"},
{replyId: 18, comment: "data", comment_author: "data"}
]},
]}
这里有一些非常简单的表格 onClick 事件函数,用于显示适当的页面
function topicOnClick (node, topic){
'use strict';
node.on("click", function() {
showSingleTopic(topic);
});
}
function threadOnClick (node, topic){
'use strict';
node.on("click", function() {
showComments(topic);
});
}
这是我的数组引用函数:
function getSingleTopic(someTopics, topicTitle) {
return someTopics.find(function (topic) {
return topic.title === topicTitle;
});
}
function getSingleComment(someTopics, topicTitle) {
return someTopics.find(function (topic) {
return topic.contents === topicTitle;
});
}
以下是试图通过表格元素将数组元素呈现给屏幕的循环:
function showSingleTopic (topicDetails){
'use strict';
var page = $("#individualForumPage");
var individualTopicTable = $("<table class='forumTable'><tr><th>Contents</th><th>Author</th></tr></table>");
for (index in topicDetails.posts) {
var post = topicDetails.posts[index];
var row = $("<tr></tr>");
row.append("<td>" + post.contents + "</td>");
row.append("<td>" + post.author + "</td>");
threadOnClick(row, topics[index]);
individualTopicTable.append(row);
}
page.html(individualTopicTable);
}
这是不显示在屏幕上的重复函数(也不检索数组元素):
function showComments (commentDetails){
'use strict';
var page = $("#commentsPage");
var commentTable = $("<table class='forumTable'><tr><th>Author</th><th>Comments</th></tr></table>");
for (index in commentDetails.replies) {
var reply = commentDetails.replies[index];
var row = $("<tr></tr>");
row.append("<td>" + reply.comment_author + "</td>");
row.append("<td>" + reply.comment + "</td>");
commentTable.append(row);
}
page.html(commentTable);
}
【问题讨论】:
-
您确定
commentDetails包含您认为的内容吗?您是否做过类似console.log(commentDetails)的操作或使用调试器查看变量的内容?作为旁注,您 shouldn't usefor ... infor arrays 改为使用for ... of
标签: javascript jquery arrays for-loop var