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 'close':removeNode(el.parentNode);break; } } }
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('praise-total')[0]; var oldTotal = parseInt(praiseElement.getAttribute('total')); var txt = el.innerHTML; var newTotal = 0; if(txt == '赞'){ newTotal = oldTotal + 1; praiseElement.innerHTML = (newTotal == 1) ? '我觉得很赞' : '我和' + oldTotal +'个人觉得很赞'; el.innerHTML = '取消赞'; }else{ newTotal = oldTotal - 1; praiseElement.innerHTML = (newTotal == 0) ? '' : newTotal + '个人觉得很赞'; el.innerHTML = '赞'; } praiseElement.setAttribute('total',newTotal); praiseElement.style.display = (newTotal == 0) ? 'none': 'block'; } //事件代理 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 'close':removeNode(el.parentNode);break; case 'praise':praiseBox(el.parentNode.parentNode.parentNode,el); } } }
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('textarea')[0]; textarea.onfocus = function(){ this.parentNode.className = 'text-box text-box-on'; this.value = (this.value == '评论...') ? '':this.value; } textarea.onblur = function(){ if(this.value == ''){ this.parentNode.className = 'text-box'; this.value = '评论...'; } }
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 == ''){ me.parentNode.className = 'text-box'; me.value = '评论...'; } },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 = 'btn btn-off'; }else{ btn.className = 'btn'; } word.innerHTML = len + '/140'; }
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('textarea')[0]; var list = box.getElementsByClassName('comment-list')[0]; var p = document.createElement('p'); p.className = 'comment-box clearfix'; p.setAttribute('user','self'); var html = ' <img class="myhead lazy" src="/static/imghwm/default1.png" data-src="images/my.jpg" alt="" />'+ '<p class="comment-content">'+ '<p class="comment-text"><span class="user">我:</span>'+textarea.value+'</p>'+ '<p class="comment-time">'+ getTime()+ '<a href="javascript:;" rel="external nofollow" rel="external nofollow" class="comment-praise" total="0" my="0" >赞</a>'+ '<a href="javascript:;" rel="external nofollow" rel="external nofollow" class="comment-operate">删除</a>'+ '</p>'+ '</p>'; p.innerHTML = html; list.appendChild(p); textarea.value = ''; 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: '0' + m; d = d>10 ? d: '0' + d; h = h>10 ? h: '0' + h; mi = mi>10 ?mi: '0' +mi; return y + '-' + m + '-' + d + ' ' + h + ':' + mi; } }
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('total')); var my = parseInt(el.getAttribute('my')); var newTotal = 0; if(my == 0){ newTotal = oldTotal + 1; el.setAttribute('total',newTotal); el.setAttribute('my',1); el.innerHTML = newTotal + '取消赞'; }else{ newTotal = oldTotal - 1; el.setAttribute('total',newTotal); el.setAttribute('my',0); el.innerHTML = (newTotal == 0) ? '' : newTotal + '赞'; } el.style.display = (newTotal == 0) ? '' : 'inline-block'; }
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('textarea')[0]; var user = commentBox.getElementsByClassName('user')[0]; var txt = el.innerHTML; if(txt == '回复'){ textarea.onfocus(); textarea.value = '回复' + user.innerHTML; textarea.onkeyup(); } else{ removeNode(el.parentNode.parentNode.parentNode); } }
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!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
