簡體   English   中英

如何計算文本區域中的字符?

[英]How can I count the characters from a textarea?


我正在嘗試為我的 `textarea` 標簽實現一個字符計數器,但某些東西肯定是行不通的。 我嘗試了幾種方法,但都沒有成功。 我知道 web 上有很多實現,但我找不到適用於我的代碼的東西。 我是這個領域的初學者,我根本無法理解它是如何工作的。 代碼:
 ............... <div id='id_text' class="control-group"> <label for="id_text" class="control-label"> Text </label> <div class="controls"> <label for="field"></label> <textarea id="field" onkeydown="countChar(this)" maxlength="800"></textarea> </div> <span>Char Left:</span> <span id="charNum"> </span> </div>....................................

腳本:

 <script src="http://code.jquery.com/jquery-1.5.js"></script> <script> function countChar(val) { var len = val.value.length; $('#charNum').text(800 - len); } </script>

注意:該腳本位於 HTML 頁面的底部(我試圖將其放在頂部,但徒勞無功)。 腳本很簡單:我只想從 textarea 中獲取字符數,然后將剩余的字符顯示給用戶。

我在這里尋找其他答案,我在其他網站上尋找答案,但我認為我的代碼有問題,我不明白。

注意 2: textarea 是<form>的一部分。 我正在使用 django 框架。

非常感謝您的幫助和關注!

編輯:

我已經嘗試了 Rory 的代碼,這就是我所看到的。

計算文本區域中的字符,您在 JavaScript 中有兩種方法

  1. 要計算單詞之間的空格字符,您只需要獲取 texarea 的內容,並測量“長度”。 請記住: “字符串原型 object 有一個初始值為 0 的“長度”屬性

 //injecting "hello world" (10 characters and 1 space) into the DOM let newDiv = document.createElement("div") let newContent = document.createTextNode(`hello world`) newDiv.setAttribute("id", "Div1") newDiv.appendChild(newContent) document.body.appendChild(newDiv) let str = document.getElementById("Div1").innerHTML //counting the number of characters injected alert(`LENGHT = ` + `${str.length}`); // HERE THE PROPERTY LENGTH..

  1. 這里計數字符沒有單詞之間的空格“:

 //injecting "hello world" (10 characters and 1 space) into the DOM let newDiv = document.createElement("div") let newContent = document.createTextNode(`hello world`) newDiv.setAttribute("id", "Div1") newDiv.appendChild(newContent) document.body.appendChild(newDiv) let str = document.getElementById("Div1").innerHTML //first you split the content using String.prototype.split ( separator, limit ) then concatenate the array obtained by the split without spaces using: Array.prototype.join ( separator ) alert(str.split(' ').join('').length)

更新:關於性能遵循@jallmer 的想法使用方法replace + REGEX

 //injecting "hello world" (10 characters and 1 space) into the DOM let newDiv = document.createElement("div") let newContent = document.createTextNode(`hello world`) newDiv.setAttribute("id", "Div1") newDiv.appendChild(newContent) document.body.appendChild(newDiv) //testing algorithms perfs let str1 = document.getElementById("Div1").innerHTML let str2= document.getElementById("Div1").innerHTML //testing algorithm 1 console.log(`str1 = ${str1}`) const t0 = performance.now(); console.log(str1.split(' ').join('').length) const t1 = performance.now() console.log(`algorithm 1 took ${t1 - t0} milliseconds.`); //testing method 2 console.log(`str2 = ${str2}`) const t2 = performance.now(); console.log(str2.replace(/\s/g, '').length) const t3 = performance.now() console.log(`algorithm 2 took ${t3 - t2} milliseconds.`);

奇怪的是,我的 chrome 開發工具(Chrome for Gnu/Linux,版本 90.0.4430.93(官方構建)(64 位))的結果不同。 需要檢查的東西比較了這兩種算法,呈現了兩種截然不同的表現:String.split().join().length vs String.replace().length。結果取決於您使用的解釋器(代碼片段與 chrome 開發工具)

keydown事件在字段中的值更新之前觸發。 因此,您的 JS 正在顯示上一次按鍵的字符計算。 keyup是兩者中更好的選擇。

但是,話雖如此,您應該改用input事件,因為它涵蓋了字段值更改而keydown / keyup不會更改的所有情況 - 例如使用鼠標復制和粘貼。

另請注意,jQuery 1.5 已嚴重過時 - 實際上已有 10 多年的歷史。 您應該使用在回答時為 3.6 的最新版本。 此外,使用onX事件屬性不再是好的做法。 在 HTML 中不包含任何 JS 的情況下,以不顯眼的方式附加您的事件處理程序。 當您已經使用 jQuery 時,您可以使用on()方法來做到這一點

說了這么多,試試這個:

 jQuery($ => { const $charNum = $('#charNum'); $('#field').on('input', e => { let len = e.target.value.length; $charNum.text(800 - len); }).trigger('input'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <div id='id_text' class="control-group"> <label for="id_text" class="control-label">Text</label> <div class="controls"> <label for="field"></label> <textarea id="field" maxlength="800"></textarea> </div> <span>Char Left:</span> <span id="charNum"> </span> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM