Javascript 如何使用javascript计算DIV中的字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8248339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:18:27  来源:igfitidea点击:

How to count the number of characters in a DIV with javascript

javascriptjqueryhtmldomcount

提问by eastboundr

Hi I want to be able to count the number of displayed characters in a Div with javascript/jquery. For example

嗨,我希望能够使用 javascript/jquery 计算 Div 中显示的字符数。例如

<div id=mydiv>
<p>This is my div!</p>
</div>

I want to get the number 15 since that's how many chars in the div including spaces.

我想得到数字 15,因为这是 div 中包含空格的字符数。

Thanks!

谢谢!

回答by Marc B

$('#mydiv').text().length

should do the trick.

应该做的伎俩。

回答by ShankarSangoli

Try this. I am trimming to avoid any white spaces in the content start or end.

尝试这个。我正在修剪以避免内容开始或结束中的任何空格。

$.trim($("#mydiv").text()).length

If you want to keep spaces also in the count then don't trim it just use this.

如果您想在计数中也保留空格,则不要修剪它,只需使用它即可。

$("#mydiv").text().length

回答by Smamatti

Sample
http://jsfiddle.net/TrMRB/

示例
http://jsfiddle.net/TrMRB/

$("#mydiv p").text().length;