简体   繁体   English

使用HTML和Javascript进行评论

[英]Comment using HTML and Javascript

I have a task to create like comment box in the HTML and Javascript How to delete comment using button delete? 我有一个在HTML和Javascript中创建类似注释框的任务如何使用按钮删除来删除注释? or should i use linked list in this task? 还是我应该在此任务中使用链表? This is my code: 这是我的代码:

<html>
    <body>
        <div id='container'>
            <textarea id='txt'></textarea><br/>
            <button type='button' onclick="add()">Enter</button>
            <div id='contents'></div>
        </div>

        <script>
            function add(){
                var txt= document.getElementById('txt').value;
                var content= document.getElementById('contents');
                var tes= '<hr/><span>'+txt+"</span><button type='button'>delete</button>";
                content.innerHTML+=tes;
            }
        </script>
    </body>
</html>

To answer the question quick, if you wanna stick with pure javascript, you can remove element from DOM using his Parent, take a look at this Remove element by id 为了快速回答这个问题,如果您想使用纯JavaScript,可以使用其Parent从DOM中删除元素,并通过id查看此Remove元素

PS Don't you need a way to store your comments somewhere (database?) 附注:您是否不需要一种将注释存储在某处的方法(数据库?)

PS2 You should avoid using html tags directly in a string assigned to a variable. PS2您应该避免在分配给变量的字符串中直接使用html标记。 Maybe you should take a look at some best practice over the web (regarding DOM manipulation, jQuery clone() method etc) 也许您应该看看网络上的一些最佳实践(关于DOM操作,jQuery clone()方法等)

Hope it helps 希望能帮助到你

It seems to me that you're not worried about persisting your data. 在我看来,您不必担心持久化数据。 So the quickest fix would be: 因此最快的解决方法是:

   <script>
            var arr = 1;
            function del(comm_id){
               var dom =document.getElementById(comm_id);
               dom.parentNode.removeChild(dom);
            }

        function add(){
            var txt= document.getElementById('txt').value;
            var content= document.getElementById('contents');
            var comm_id="comment"+arr;
            var del_id="delete"+arr;
            var tes= "<div id="+comm_id+">"+'<hr/><span>'+txt+"</span><button type='button' id="+ del_id + ">delete</button></div>";
            content.innerHTML+=tes;
             document.getElementById(del_id).setAttribute('onclick',"del('"+comm_id+"')");
            arr++;
        }
    </script>

For this there is no need of implementing Linked List. 为此,无需实现链接列表。 You can make use of Array in javascript. 您可以在javascript中使用Array。 There is no need of pre-defining the size of array. 无需预先定义数组的大小。 You can add any number of elements in it. 您可以在其中添加任意数量的元素。

To remove a particular element you can make use of 要删除特定元素,您可以利用

array.splice(i, 1);

This will remove the ith element. 这将删除第ith个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM