一个长长的问题,所以我会削减权利的追逐。我已经建立了包含一些内容与内容子阵列设置一个变量数组如下:(小片段只是为了让事情的想法)Jquery/JavaScript - 检索数组变量
var topics = [
{title: "Football Topics", followers: 280, articles: 5, posts: [
{postId: 101, contents: "Dummy content", replies:[
{replyId: 1, contents: "Dummy content", author: "Boys_In_Blue"},
{replyId: 2, contents: "Dummy content", author: "Blue-baggers"},
{replyId: 3, contents: "Dummy content", author: "Chelsea_2017"}
]}
]}
];
在这阵,我打算设置在一些表格div内建立一个模拟论坛系统。核心功能起作用,因为用户可以与设置的初始表屏幕进行交互,显示一个表明足球话题的table_row,但是在点击事件时,我只会看到未定义的表格内容,因为我不确定如何检索我试图访问的适当数据。我遇到的主要困惑和复杂性在于能够检索这些变量(即,replyId,内容和作者)并根据之前的论坛属性设置来呈现它们 - 意味着如果用户选择“足球话题”,他们只会被提供适当的足球相关话题等。
感谢任何帮助!
//onClick function
function topicOnClick (node, topic){
'use strict';
node.on("click", function() {
showSingleTopic(topic);
});
}
//function for showing initial forum page
function showForum() {
'use strict';
$(".homePage").hide();
$("#registerPage").hide();
$("#aboutPage").hide();
$("#loginPage").hide();
$("#browsePage").show();
var page = $("#browsePage");
var topicTable = $("<table class='forumTable'><tr><th>Title</th><th>Posts</th><th>Followers</th></tr></table>");
//console test
//console.log(topics);
//Looping all topics in variable "topics"
for (index in topics) {
//console test
console.log(topics[index].title);
var row = $("<tr></tr>");
row.append("<td>" + topics[index].title + "</td>");
row.append("<td>" + topics[index].articles + "</td>");
row.append("<td>" + topics[index].followers + "</td>");
topicOnClick(row, topics[index]);
topicTable.append(row);
}
page.append(topicTable);
//Finally, add the page to our web app
$("#maincontent").html(page);
}
//this function isn't working in the ways I want it to as I'm not sure how to retrieve my replyId, contents and author from within my array
function showSingleTopic (topicDetails){
'use strict';
alert(topicDetails.title);
$(".homePage").hide();
$("#registerPage").hide();
$("#aboutPage").hide();
$("#loginPage").hide();
$("#browsePage").hide();
var page = $("#individualForumPage");
//page.append("<h1>"topicDetails.title"</h1>")
var individualTopicTable = $("<table class='forumTable'><tr><th>Contents</th><th>Author</th><th>Replies</th></tr></table>");
//Looping all topics in variable "topics"
for (index in topics) {
//console test
console.log(topics[index].postId);
var row = $("<tr></tr>");
row.append("<td>" + topics[index].contents + "</td>");
row.append("<td>" + topics[index].author + "</td>");
row.append("<td>" + topics[index].replies + "</td>");
//topicOnClick(row, topics[index]);
individualTopicTable.append(row);
}
page.append(individualTopicTable);
//Finally, add the page to our web app
$("#maincontent").html(page);
}
你会得到更快的/有[MCVE] – Jamiec
更好的答案除了通过@Jamiec发表评论。在这些情况下,分割“数据”和“渲染”功能通常很有用。例如,不要试图通过将代码添加到页面来立即测试您的代码。创建一个名为'getSingleTopic'的函数并首先进行测试。它应该有你的数据集作为输入,以及它应该选择的主题。它应该返回另一个对象/数组,只有你感兴趣的东西。'showSingleTopic'应该在那个输出上工作,并且只把它绘制到屏幕上。 – shotor
去lodash库它有一些很酷的方法。 – zabusa