javascript 使用 jQuery 计算段落中的字符(*not* for input/textarea)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5120736/
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-10-25 16:01:34  来源:igfitidea点击:

Count characters in paragraph using jQuery (*not* for input/textarea)

javascriptjqueryhtml

提问by Adi

How do I work out in jQuery a character counter of a p/div tag?

如何在 jQuery 中计算出 ap/div 标签的字符计数器?

Basically i want to show a different css value IF the character value >=50.

基本上我想显示不同的 css 值,如果字符值 >=50。

Been struggling for hours with it :)

已经为此苦苦挣扎了几个小时:)

回答by Anurag

Use

利用

$("#myDiv").text().length;

回答by jevakallio

var $div = $('#mydiv');
if($div.text().length >= 50) {
    $div.addClass('class');
}

回答by Phrogz

Put a "long"class on alldiv and p elements with more than 50 characters:

"long"所有超过 50 个字符的 div 和 p 元素上放置一个类:

$("p, div").filter(function(){
  return $(this).text().length >=50;
}).addClass('long');

If you don't know how much content you have, though, then presumably this content is generated dynamically by the server, right? And if this is the case, wouldn't it make more sense to have the server—which knows how much content it's plopping into these containers—add the class dynamically while generating the page to send? Why rely on jQuery?

但是,如果您不知道自己拥有多少内容,那么大概这些内容是由服务器动态生成的,对吗?如果是这种情况,让服务器(它知道将多少内容放入这些容器中)在生成要发送的页面时动态添加类不是更有意义吗?为什么要依赖 jQuery?

回答by Youssof H.

Try this snippet it works even if the text's length was greater than 50 characters.

试试这个片段,即使文本的长度大于 50 个字符,它也能工作。

You can also calculate the character digits of the paragraph. (Excluding new lines and space bars)

您还可以计算段落的字符位数。(不包括换行符和空格键)

window.setInterval(function() {
  var txt = $("#txt").val();
  var parLength = $("#data").text().length;
  var charLength = txt.replace(/ /g, '').replace(/\n/g, '').length;
  $("#data").text(txt);
  $("#calcLength").text("The paragrapgh's length is: " + parLength);
  $("#calcChar").text("The amount of characters is: " + charLength);
}, 10);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="txt" placeholder="Enter text here..." style="height:100px;width:250px"></textarea>
<p id="data"></p>
<p id="calcLength"></p>
<b>Note: even a space character is calculated through the length function</b>
<p id="calcChar"></p>
<b>Note: a space bar,and every empty line is trimmed in the second calculated value</b>

I have provided this example to make it simple for use and compatability.

我提供了这个例子来简化使用和兼容性。