Home Web Front-end JS Tutorial Use JavaScript to implement comment and like functions

Use JavaScript to implement comment and like functions

Mar 20, 2017 pm 03:03 PM

By analyzing the logical relationship of the comment function, learn how to use JavaScript to implement various functions such as comments, replies, and likes. This article mainly introduces how to implement the JavaScript comment and like function. Friends who need it can refer to

By analyzing the logical relationship of the comment function, you can learn how to use Javascript to implement various functions such as comments, replies, and likes.

1. Learn how to handle date and time with Javascript.

2. Master the method of adding/deleting child nodes in Dom operations.

3. Use setTimeout to set the timer.

4. Use clearTimeout to clear the timer and use the event agent.

Rendering:

1) Implement the function of deleting shared content

Use the event proxy to delete the shared content by clicking the close button.

Delete events:

Use the event proxy function to add events on the parent element node to reduce the amount of code and system running load.

When event proxying, use events The srcElement attribute in the object gets the trigger element.

IE browser supports window.event.srcElement, and firefox supports window.event.target.

So, if you want to be compatible in firefox, you only need to change one code: change var el = e.srcElement to var el = e.srcElement || e.target

removeChild() refers to Delete the child element, so to delete the current element el, first use parentNode to find the parent node, and then use removeChild(el) to delete the el element.

var list = document.getElementById('list');
      var boxs = document.getElementsByClassName('box');
      //删除节点函数
      function removeNode(node){
        node.parentNode.removeChild(node);
      }
      //事件代理
      for(var i=0 ;i<boxs.length;i++){
        boxs[i].onclick = function(e){
          e = e||window.event;
          var el = e.srcElement || e.target;
          switch (el.className) {
            case &#39;close&#39;:removeNode(el.parentNode);break;
          }
        }
      }
Copy after login

2) Implement the like function of sharing

Constructing a like and share function requires two parameters. The first parameter (box) represents the outermost parent of the like. Container, the second parameter (el) refers to the triggered element, that is, the like button

getAttribute() to get the attributes, and use setAttribute() to set the attributes of the element.

js code:

//点赞分享
      function praiseBox(box,el){//box为所触发元素el的最外层父容器
        var praiseElement = box.getElementsByClassName(&#39;praise-total&#39;)[0];
        var oldTotal = parseInt(praiseElement.getAttribute(&#39;total&#39;));
        var txt = el.innerHTML;
        var newTotal = 0;
        if(txt == &#39;赞&#39;){
          newTotal = oldTotal + 1;
          praiseElement.innerHTML = (newTotal == 1) ? &#39;我觉得很赞&#39; : &#39;我和&#39; + oldTotal +&#39;个人觉得很赞&#39;;
          el.innerHTML = &#39;取消赞&#39;;
        }else{
          newTotal = oldTotal - 1;
          praiseElement.innerHTML = (newTotal == 0) ? &#39;&#39; : newTotal + &#39;个人觉得很赞&#39;;
          el.innerHTML = &#39;赞&#39;;
        }
        praiseElement.setAttribute(&#39;total&#39;,newTotal);
        praiseElement.style.display = (newTotal == 0) ? &#39;none&#39;: &#39;block&#39;;
      }
      //事件代理
      for(var i=0 ;i<boxs.length;i++){
        boxs[i].onclick = function(e){
          e = e||window.event;
          var el = e.srcElement || e.target;
          switch (el.className) {
            case &#39;close&#39;:removeNode(el.parentNode);break;
            case &#39;praise&#39;:praiseBox(el.parentNode.parentNode.parentNode,el);
          }
        }
      }
Copy after login

3) Implement the comment function

First of all, you must implement the change of the comment input box, by listening to three events

1. Obtain When the focus is on: onfocus

2. When the focus is lost: onblur

3. When the mouse input pops up: onkeyup

//输入框
        var textarea = boxs[i].getElementsByTagName(&#39;textarea&#39;)[0];
        textarea.onfocus = function(){
          this.parentNode.className = &#39;text-box text-box-on&#39;;
          this.value = (this.value == &#39;评论...&#39;) ? &#39;&#39;:this.value;
        }
        textarea.onblur = function(){
          if(this.value == &#39;&#39;){
            this.parentNode.className = &#39;text-box&#39;;
            this.value = &#39;评论...&#39;;
          }
        }
Copy after login

4) Implement the reply button and word count functions

Add the onkeyup keyboard pop-up event to the textarea and learn to use the method of obtaining the parent node and child node.

In order to provide a better user experience, the input box will not immediately become smaller when it loses focus, so add a timer function in onblur. Note that the timer must be cleared when the gray reply button is clicked

js code:

textarea.onblur = function(){
          var me = this;//因为有定时器所以先将this存放于变量中
          timer = setTimeout(function(){
            if(me.value == &#39;&#39;){
              me.parentNode.className = &#39;text-box&#39;;
              me.value = &#39;评论...&#39;;
            }
          },500);
        }
        textarea.onkeyup = function(){
          var len = this.value.length;
          var p = this.parentNode;
          var btn = p.children[1];
          var word = p.children[2];
          if(len == 0 || len > 140){
            btn.className = &#39;btn btn-off&#39;;
          }else{
            btn.className = &#39;btn&#39;;
          }
          word.innerHTML = len + &#39;/140&#39;;
        }
Copy after login

5) Implement the comment sharing function

When the reply button is clicked, the content of the input box is added to the reply list by creating a p and adding a reply list, pay attention to changing part of the new reply list and the date of the comment to be changed.

js code:

//发表评论
      function replayBox(box){
        var textarea = box.getElementsByTagName(&#39;textarea&#39;)[0];
        var list = box.getElementsByClassName(&#39;comment-list&#39;)[0];
        var p = document.createElement(&#39;p&#39;);
        p.className = &#39;comment-box clearfix&#39;;
        p.setAttribute(&#39;user&#39;,&#39;self&#39;);
        var html = &#39; <img src="images/my.jpg" class="myhead" alt="" />&#39;+
            &#39;<p class="comment-content">&#39;+
            &#39;<p class="comment-text"><span class="user">我:</span>&#39;+textarea.value+&#39;</p>&#39;+
            &#39;<p class="comment-time">&#39;+
            getTime()+
            &#39;<a href="javascript:;" rel="external nofollow" rel="external nofollow" class="comment-praise" total="0" my="0" style="">赞</a>&#39;+
            &#39;<a href="javascript:;" rel="external nofollow" rel="external nofollow" class="comment-operate">删除</a>&#39;+
            &#39;</p>&#39;+
            &#39;</p>&#39;;
        p.innerHTML = html;
        list.appendChild(p);
        textarea.value = &#39;&#39;;
        textarea.onblur();
        function getTime(){
          var t = new Date();
          var y = t.getFullYear();
          var m = t.getMonth() + 1;//月份是从0开始
          var d = t.getDay();
          var h = t.getHours();
          var mi = t.getMinutes();
          m = m>10 ? m: &#39;0&#39; + m;
          d = d>10 ? d: &#39;0&#39; + d;
          h = h>10 ? h: &#39;0&#39; + h;
          mi = mi>10 ?mi: &#39;0&#39; +mi;
          return y + &#39;-&#39; + m + &#39;-&#39; + d + &#39; &#39; + h + &#39;:&#39; + mi;
        }
      }
Copy after login

5) Implement the like reply function

There is a my attribute in the a tag of the like button, which indicates whether you have liked it. When my When the value is 0, total will increase by one when the like button is clicked. When my value is 1, total will decrease by one when the like button is clicked.

js code:

//点赞回复
      function praiseReplay(el){
        var oldTotal = parseInt(el.getAttribute(&#39;total&#39;));
        var my = parseInt(el.getAttribute(&#39;my&#39;));
        var newTotal = 0;
        if(my == 0){
          newTotal = oldTotal + 1;
          el.setAttribute(&#39;total&#39;,newTotal);
          el.setAttribute(&#39;my&#39;,1);
          el.innerHTML = newTotal + &#39;取消赞&#39;;
        }else{
          newTotal = oldTotal - 1;
          el.setAttribute(&#39;total&#39;,newTotal);
          el.setAttribute(&#39;my&#39;,0);
          el.innerHTML = (newTotal == 0) ? &#39;&#39; : newTotal + &#39;赞&#39;;
        }
        el.style.display = (newTotal == 0) ? &#39;&#39; : &#39;inline-block&#39;;
      }
Copy after login

6) Implement the deletion and reply function of the content in the reply list

Reply to other people’s comments and delete your own comments

js code:

 //操作回复
      function operateReply(el){
        var commentBox = el.parentNode.parentNode.parentNode;//评论的容器
        var box = commentBox.parentNode.parentNode.parentNode;//该条分享的容器
        var textarea = box.getElementsByTagName(&#39;textarea&#39;)[0];
        var user = commentBox.getElementsByClassName(&#39;user&#39;)[0];
        var txt = el.innerHTML;
        if(txt == &#39;回复&#39;){
          textarea.onfocus();
          textarea.value = &#39;回复&#39; + user.innerHTML;
          textarea.onkeyup();
        }
        else{
          removeNode(el.parentNode.parentNode.parentNode);
        }
      }
Copy after login

The above is the detailed content of Use JavaScript to implement comment and like functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles