简体   繁体   中英

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? 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

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. Maybe you should take a look at some best practice over the web (regarding DOM manipulation, jQuery clone() method etc)

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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