中附加在第一篇文章上的评论

中附加在第一篇文章上的评论

本文介绍了仅在 Vanilla JavaScript 中附加在第一篇文章上的评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个状态发布和评论系统.它是在 Vanilla JavaScript 中实现的.任何人都可以添加帖子并对帖子发表评论.一切正常,但评论部分仅在第一篇文章中工作.删除评论和帖子工作正常.我不知道是什么问题,如果有人可以帮助我..这是 HTML 代码

 

<div class="create-post"><表格><div class="form-group"><div class="username"><p class="name";style="top:15px;">用户名</p>

<p class="qoutes"><textarea 样式="字体大小:15pt;"类=表单控制"id =输入帖子"行=7"id="mypara"placeholder="分享你的想法..."></textarea></p><div class="postbar"><按钮类型=按钮";class =btn btn-primary post-me"id="post-button"><span id="postText">发布</span></button>

</表单>

<hr class="line-bar"><div class="allpost"><div class="mainpost";id=后div"></div>

这里是 JavaScript 代码

showTask();显示评论();让 addPost = document.getElementById("enter-post");让 addPostBtton = document.getElementById("post-button");addPostBtton.addEventListener(点击",函数(){var addPostVal = addPost.value;如果(addPostVal.trim()!= 0){let webtask = localStorage.getItem(localtask");如果(网络任务 == 空){var taskObj = [];}别的 {taskObj = JSON.parse(webtask);}taskObj.push(addPostVal);localStorage.setItem(localtask", JSON.stringify(taskObj));}显示任务();});函数 showTask() {let webtask = localStorage.getItem(localtask");如果(网络任务 == 空){var taskObj = [];}别的 {taskObj = JSON.parse(webtask);}让 htmlVal = '';让 createPost = document.getElementById("post-div");taskObj.forEach((item, index) => {htmlVal += `<div class="post-class"><div class="username u-name"><p class="name i-name">${"User Name "+ 索引}

<i class="fas fa-trash-alt";onclick="removePost(${index});"></i></button>

<小时><p class="quotes">${item}</p><div class="comment-section";id=评论部分"><p class="comment-qoute"><textarea 样式="字体大小:15pt;"class="form-control commentBox";行=3"id="mypara"placeholder="留下评论"></textarea></p><button class="btn btn-primary comment-btn";id=commentBtn">comment</button><ul class="comments";id=评论部分"><p></p>

<br><br>`});createPost.innerHTML = htmlVal;}函数 removePost(index) {let webtask = localStorage.getItem(localtask");让 taskObj = JSON.parse(webtask);taskObj.splice(index, 1);localStorage.setItem(localtask", JSON.stringify(taskObj));显示任务();}var commentPost = document.getElementById('mypara');var commentBtn = document.getElementById('commentBtn');commentBtn.addEventListener('click', function () {var commentValue = commentPost.value;如果(commentValue.trim()!= 0){let commentTask = localStorage.getItem("comments");if (commentTask == null) {var commentObj = [];}别的 {commentObj = JSON.parse(commentTask);}commentObj.push(commentValue);localStorage.setItem("comments", JSON.stringify(commentObj));}显示评论();});函数 showComment() {let commentsTask = localStorage.getItem("comments");if (commentsTask == null) {var commentObj = [];}别的 {commentObj = JSON.parse(commentsTask);}让 commentHTMLValue = '';var createComment = document.getElementById("comments-partion");commentObj.forEach((item, index) => {commentHTMLValue += `<div class="comment-box-btn"><p>${index + "."}<span>${item}</span></p><i class="far fa-times-circle fa-2x";onclick="removeComment(${index});"></i>

`;});createComment.innerHTML = commentHTMLValue;}var deleteBtn = document.querySelector('.comment-del');deleteBtn.addEventListener('click', () => {});//删除注释功能删除评论(索引){let commentTask = localStorage.getItem("comments");让 commentObj = JSON.parse(commentTask);commentObj.splice(index, 1);localStorage.setItem("comments", JSON.stringify(commentObj));显示评论();}

解决方案

我不能在这里做一个片段,因为不允许使用 localStorage.将此块复制到一个空白文件中并将其另存为 html 文件,然后在浏览器中打开它.

这就是我认为您描述您的要求的方式,也是基于我评论中的数据格式.它不漂亮,需要大量修饰,但它可以运行.

<META HTTP-EQUIV=内容类型"内容=文本/html;字符集=UTF-8"><头><title>任务列表</title><script type="text/javascript">让 taskList = [];函数检查任务(){让tasksList = getTasksList();如果(tasksList.length == 0){let newTask = prompt("请输入任务描述");如果(新任务){让 thisIndex = getNewIndex();让 a = {id":thisIndex,task":newTask,comments":[]}taskList.push(a);saveTasksList(taskList);}}显示任务();}函数显示任务(){let container = document.getElementById(tasks");container.innerHTML = ";让 taskList = getTasksList();taskList.forEach(函数(任务){让 d = document.createElement(div");d.id = task_"+ 任务编号;d.className = "commentdiv";d.innerHTML = 

"+ task.task +

";让 l = document.createElement(ul");l.id = "comments_";+ 任务编号;让评论 = task.comments;如果(评论长度> 0){让评论索引 = 0;评论.forEach(功能(评论){让 c = document.createElement(li");c.innerHTML = 评论;让 cb = document.createElement(按钮");cb.id = "deletecomment_";+ task.id + "_";+ 评论索引;cb.innerHTML = "删除评论";cb.onclick = function() {deleteComment(task.id, commentindex);};c.appendChild(cb);l.appendChild(c);})}让 b = document.createElement(按钮");b.id = "addcomment_";+ 任务编号;b.onclick = function() {addComment(task.id);};b.innerHTML = "添加评论";d.appendChild(b);d.appendChild(l);container.appendChild(d);})}函数添加注释(taskid){let newcomment = prompt(输入评论");如果(新评论){让 tasklist = getTasksList();让过滤 = tasklist.filter(task => task.id == taskid);如果(过滤[0]){让 thisTask = 过滤 [0];thisTask.comments.push(newcomment);让 thisIndex = taskList.findIndex((task) => task.id == taskid);taskList[thisIndex] = thisTask;}saveTasksList(taskList);显示任务();}}函数 addNewTask() {let newTask = prompt(输入任务描述");让 taskList = getTasksList();让 lastindex = localStorage.getItem(tasksindex");让 index = getNewIndex();让 a = {id":索引,任务":newTask,评论":[]}taskList.push(a);saveTasksList(taskList);显示任务();}函数 deleteComment(taskid,commentindex){让 tasklist = getTasksList();让过滤 = tasklist.filter(task => task.id == taskid);//只要有至少一个task有taskid值,就查找并删除评论//基于评论在评论数组中的索引位置如果(过滤[0]){让 thisTask = 过滤 [0];thisTask.comments.splice(commentindex, 1);让 thisIndex = taskList.findIndex((task) => task.id == taskid);taskList[thisIndex] = thisTask;}saveTasksList(taskList);显示任务();}函数 getTasksList() {let tasks = localStorage.getItem("tasks");taskList = JSON.parse(tasks);如果(!任务列表){任务列表 = [];}返回任务列表;}函数 saveTasksList(taskList) {localStorage.setItem("tasks", JSON.stringify(taskList));}函数 getNewIndex() {让 lastindex = localStorage.getItem(tasksindex");让 idx = 0;如果(!lastindex){idx = 1;} 别的 {idx = Number(lastindex) + 1;}localStorage.setItem("tasksindex", idx);返回idx;}函数 removeAll() {localStorage.removeItem(任务");localStorage.removeItem(tasksindex");显示任务();}window.onload = checkTasks;<style type="text/css">.commentdiv {边框:1px纯黑色;宽度:1000px;填充:5px;边框半径:5px;}按钮 {左边距:10px;}h3{宽度:100%;边框底部:1px 黑色虚线;}ul{列表样式类型:十进制;}</风格><身体><h2>我的任务列表 <button id="addNewTaskButton";onclick="addNewTask();">添加新任务</button></h2><小时><div id="任务">

<button id="removeAll";onclick="removeAll();">删除所有任务</button></html>

I am creating a status posting and commenting system.It is implemented in Vanilla JavaScript. Anyone can add a post and can comment on the post.Everything is working fine but the comment section is working on first post only.deletion of comment and post is working fine.I don't know what's the problem is, if anyone could help me..Here is the HTML code

 <div class="container-post" id="container-post">
    <div class="create-post">
        <form>
            <div class="form-group">
                <div class="username">
                    <p class="name" style="top:15px;">User Name</p>
                </div>
                <p class="qoutes">
                    <textarea style=" font-size: 15pt;" class="form-control" id="enter-post" rows="7" id="mypara" placeholder="Share Your Thoughts..."></textarea>
                </p>
                <div class="postbar">
                    <button type="button" class="btn btn-primary post-me" id="post-button"> <span id="postText">Post</span></button>
                </div>
            </div>
        </form>
    </div>
    <hr class="line-bar">

    <div class="allpost">

        <div class="mainpost" id="post-div"></div>

    </div>

Here is the JavaSCript code

showTask();
showComment();

let addPost = document.getElementById("enter-post");
let addPostBtton = document.getElementById("post-button");

addPostBtton.addEventListener("click", function () {

var addPostVal = addPost.value;
if (addPostVal.trim() != 0) {
    let webtask = localStorage.getItem("localtask");

    if (webtask == null) {
        var taskObj = [];
    }
    else {
        taskObj = JSON.parse(webtask);
    }
    taskObj.push(addPostVal);
    localStorage.setItem("localtask", JSON.stringify(taskObj));

}

showTask();
});


function showTask() {
let webtask = localStorage.getItem("localtask");

if (webtask == null) {
    var taskObj = [];
}
else {
    taskObj = JSON.parse(webtask);
}

let htmlVal = '';
let createPost = document.getElementById("post-div");
taskObj.forEach((item, index) => {
    htmlVal += `
                <div class="post-class"><div class="username u-name">
                <p class="name i-name">${"User Name " + index}</p>
                <i class="fas fa-trash-alt" onclick="removePost(${index});"></i></button>
                </div>
                <hr>
                <p class="quotes">
                ${item}
                </p>
                <div class="comment-section" id="comment-section">
                    <p class="comment-qoute">
                        <textarea style=" font-size: 15pt;" class="form-control commentBox" rows="3" id="mypara" placeholder="Leave a comment"></textarea>
                    </p>
                    <button class="btn btn-primary comment-btn" id="commentBtn">comment</button>
                    <ul class="comments" id="comments-portion">
                        <p></p>

                    </ul>
            </div>
            </div>
                <br><br>`
});

createPost.innerHTML = htmlVal;
}

function removePost(index) {

let webtask = localStorage.getItem("localtask");
let taskObj = JSON.parse(webtask);
taskObj.splice(index, 1);
localStorage.setItem("localtask", JSON.stringify(taskObj));
showTask();
}

var commentPost = document.getElementById('mypara');
var commentBtn = document.getElementById('commentBtn');

commentBtn.addEventListener('click', function () {
var commentValue = commentPost.value;

if (commentValue.trim() != 0) {
    let commentTask = localStorage.getItem("comments");

    if (commentTask == null) {
        var commentObj = [];
    }
    else {
        commentObj = JSON.parse(commentTask);
    }
    commentObj.push(commentValue);
    localStorage.setItem("comments", JSON.stringify(commentObj));

}
showComment();
});


function showComment() {
let commentsTask = localStorage.getItem("comments");

if (commentsTask == null) {
    var commentObj = [];
}
else {
    commentObj = JSON.parse(commentsTask);
}

let commentHTMLValue = '';
var createComment = document.getElementById("comments-portion");
commentObj.forEach((item, index) => {
    commentHTMLValue += `<div class="comment-box-btn">
                            <p>${index + ". "}<span>${item}</span></p>
                            <i class="far fa-times-circle fa-2x" onclick="removeComment(${index});"></i>
                        </div>
                        `;
});

createComment.innerHTML = commentHTMLValue;
}


var deleteBtn = document.querySelector('.comment-del');
deleteBtn.addEventListener('click', () => {

});


// remove comment


function removeComment(index) {
let commentTask = localStorage.getItem("comments");
let commentObj = JSON.parse(commentTask);
commentObj.splice(index, 1);
localStorage.setItem("comments", JSON.stringify(commentObj));
showComment();
 }
解决方案

I can't do a snippet here as the use of localStorage is not allowed. Copy this block into a blank file and save it as an html file and then open that in a browser.

This is how I think you are describing your requirements and is also based on the data format in my comments. It's not pretty and needs plenty of sprucing up, but it runs.

<!DOCTYPE html>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<html>
<head>
<title>Task listing</title>

<script type="text/javascript">

let taskList = [];

function checkTasks() {
  let tasksList = getTasksList();
  if (tasksList.length == 0) {
    let newTask = prompt("Please enter a task description");
    if (newTask) {
      let thisIndex = getNewIndex();
      let a = {"id": thisIndex, "task": newTask, "comments": []}
      taskList.push(a);
      saveTasksList(taskList);
    }
  }
  displayTasks();
}

function displayTasks() {
  let container = document.getElementById("tasks");
  container.innerHTML = "";
  let taskList = getTasksList();
  taskList.forEach(function(task){
    let d = document.createElement("div");
    d.id = "task_" + task.id;
    d.className = "commentdiv";
    d.innerHTML = "<h3>" + task.task + "</h3>";
    let l = document.createElement("ul");
    l.id = "comments_" + task.id;
    let comments = task.comments;
    if (comments.length > 0) {
      let commentindex = 0;
      comments.forEach(function(comment) {
        let c = document.createElement("li");
        c.innerHTML = comment;
        let cb = document.createElement("button");
        cb.id = "deletecomment_" + task.id + "_" + commentindex;
        cb.innerHTML = "Delete comment";
        cb.onclick = function() {deleteComment(task.id, commentindex);};
        c.appendChild(cb);
        l.appendChild(c);
      })
    }
    let b = document.createElement("button");
    b.id = "addcomment_" + task.id;
    b.onclick = function() {addComment(task.id);};
    b.innerHTML = "Add comment";
    d.appendChild(b);
    d.appendChild(l);
    container.appendChild(d);
  })
}

function addComment(taskid) {
  let newcomment = prompt("Enter comment");
  if (newcomment) {
    let tasklist = getTasksList();
    let filtered = tasklist.filter(task => task.id == taskid);
    if (filtered[0]) {
      let thisTask = filtered[0];
      thisTask.comments.push(newcomment);
      let thisIndex = taskList.findIndex((task) => task.id == taskid);
      taskList[thisIndex] = thisTask;
    }
    saveTasksList(taskList);
    displayTasks();
  }
}

function addNewTask() {
  let newTask = prompt("Enter task description");
  let taskList = getTasksList();
  let lastindex = localStorage.getItem("tasksindex");
  let index = getNewIndex();
  let a = {"id": index, "task": newTask, "comments": []}
  taskList.push(a);
  saveTasksList(taskList);
  displayTasks();
}

function deleteComment(taskid, commentindex) {
  let tasklist = getTasksList();
  let filtered = tasklist.filter(task => task.id == taskid);
  // as long as there is at least one task with the taskid value, find and delete the comment
  // based on the index position of the comment in the comments array
  if (filtered[0]) {
    let thisTask = filtered[0];
    thisTask.comments.splice(commentindex, 1);
    let thisIndex = taskList.findIndex((task) => task.id == taskid);
    taskList[thisIndex] = thisTask;
  }
  saveTasksList(taskList);
  displayTasks();

}

function getTasksList() {
  let tasks = localStorage.getItem("tasks");
  taskList = JSON.parse(tasks);
  if (!taskList) {
    taskList = [];
  }
  return taskList;
}

function saveTasksList(taskList) {
  localStorage.setItem("tasks", JSON.stringify(taskList));
}

function getNewIndex() {
  let lastindex = localStorage.getItem("tasksindex");
  let idx = 0;
  if (!lastindex) {
    idx = 1;
  } else {
    idx = Number(lastindex) + 1;
  }
  localStorage.setItem("tasksindex", idx);
  return idx;
}

function removeAll() {
  localStorage.removeItem("tasks");
  localStorage.removeItem("tasksindex");
  displayTasks();

}

window.onload = checkTasks;


</script>

<style type="text/css">

.commentdiv {
  border:1px solid black;
  width:1000px;
  padding:5px;
  border-radius:5px;
}

button {
  margin-left:10px;
}

h3 {
  width:100%;
  border-bottom: 1px dotted black;
}

ul {
  list-style-type:decimal;
}

</style>
</head>
<body>
<h2>My task list <button id="addNewTaskButton" onclick="addNewTask();">Add new task</button></h2>
<hr>
<div id="tasks">

</div>
<button id="removeAll" onclick="removeAll();">Remove all tasks</button>
</body>
</html>

这篇关于仅在 Vanilla JavaScript 中附加在第一篇文章上的评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 16:49