javascript - 如何计算所有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
任何想法?
解决方案
您可以遍历所有div
s 并获取文本上下文。然后,使用空格将其拆分以获取数组或每个单词,然后添加该单词的长度x
以获取所有div
s 中的总字符。
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>
推荐阅读
- c++ - 将&符号附加到类方法
- r - 在 R 中,如何列出数据框的值?
- r - 将具有相互非排他类别的长数据转换为宽格式
- sql-server - 如何对 CTE 创建的数据使用表值函数
- python - 使用 SVC 时,FPR 和 TPR 总是获得 0.5 的 AUC
- sql - 在 SQL Server 中用 IIF 替换大小写
- android - 当服务器返回 JWT 死机时,Smooch 对话恢复
- css - 为什么我的 iphone 上的移动背景与 devtools 中的不同?
- python - TypeError:单例数组数组(True)不能被视为有效集合
- php - PHP - 电子邮件响应者中的复选框值显示