The word count function works by adding an onKeyup event to the textarea. The event reads the textarea content and obtains the length, and assigns it to the text node that counts the word count. One thing to note here is that adding onKeypress and onKeydown events can also achieve the effect. , but they all have some shortcomings and can cause misunderstandings in some cases. I have tried them all and feel that using only one onKeyup event is the wisest choice.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试文件</title> <script> function cal_words(){ var length = document.getElementById("test").value.length; document.getElementById("num").innerHTML = length; } </script> </head> <body> <div class="reply"> <textarea id="test" onKeyUp="cal_words()"></textarea> <div>字数:<span id="num">0</span></div> </div> </body> </html>
The above is the entire content of this article, I hope you all like it.