jQuery / JavaScript防止重复追加

时间:2017-08-02 02:53:11

标签: javascript jquery append

看似微不足道的问题我正在使用模拟论坛系统我正在尝试原型,因为以下数组和表格功能我创建了重复的论坛表格由于附加我已经使用了,而且我不确定如何避免这种情况或修改此问题(即,如果用户反复点击论坛页面,论坛将重复生成)。我仍然对语言非常了解,但从我在类似帖子中发现的内容来看,我尝试申请的所有内容都没有解决问题。

var index;    

var topics = [      
    {title: "Football Topics", followers: 280, articles: 5, posts: [
        {postId: 101, contents: "Dummy content", author: "Dummy content", replies:[
            {replyId: 1, contents: "Dummy content", author: "Dummy content"},
            {replyId: 2, contents: "Dummy content", author: "Dummy content"},
            {replyId: 3, contents: "Dummy content", author: "Dummy content"}
        ]},
    ]}
];  

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);

1 个答案:

答案 0 :(得分:0)

根据您提供的内容,我认为有几种选择。

选项1

你说如果重复使用&#39;点击&#39;论坛页面暗示有一个点击处理程序。您可以使用最多执行该功能的.one

&#13;
&#13;
var table = "<table><tr><td>column1</td><td>column2</td></tr></table>";
$('button').one('click', function() {
  $('#tableContainer').append(table);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div id="tableContainer">
  </div>

  <button>add</button>
</body>
&#13;
&#13;
&#13;

选项2

您可以定位容器div并使用.html()这将允许该功能在每次单击时运行,但会覆盖内容,因此它只显示一次加载的外观。

&#13;
&#13;
var table = "<table><tr><td>column 1</td><td>column 2</td></tr></table>";
$('button').on('click', function(){
  $('#tableContainer').html(table);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
 <div id="tableContainer">
 </div>

<button>add</button>
</body>
&#13;
&#13;
&#13;