首页 > 解决方案 > 如何计算所有div中的字符

问题描述

我需要计算所有字符(不包括空格),divs并且仅在divs.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='parent'>
<div>a</div>
<div>b4</div>
<div>52 5</div>
<hr>
<input type='text' value='323'>

</div>

let x = // count characters in all divs;
console.log(x);

在上面的示例中,结果应该是6

任何想法?

标签: javascriptjquery

解决方案


您可以遍历所有divs 并获取文本上下文。然后,使用空格将其拆分以获取数组或每个单词,然后添加该单词的长度x以获取所有divs 中的总字符。

var x = 0;
$('.parent div').each(function(){
  $(this).text().split(/\s/g).forEach(word => x+=word.trim().length);
});
console.log(x);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='parent'>
  <div>a</div>
  <div>b4</div>
  <div>52 5</div>
  <hr>
  <input type='text' value='323'>

</div>


推荐阅读