我的任务是在我的页面上数单词,到目前为止,我的代码是计数字母。我没什么主意了。如下所示:
var profile_values = document.getElementsByClassName('profile-value');
var total_words = 0;
for (i = 0; i < profile_values.length; i++) {
total_words += profile_values[i].innerHTML.split(' ').length;
}
document.getElementById('word-count').innerHTML = total_words;<div class="profile-value">
<td>
<p>I am a profile value</p>
</td>
</div>
<div id="stats">
<h3>Stats</h3>
<span id="word-count" class="large">0</span>
<br>words found.
</div>
发布于 2016-07-14 19:07:09
您想要去掉换行符,并使用trim()修剪任何无关的空格。
var profile_values = document.getElementsByClassName('profile-value');
var total_words = 0;
for (i = 0; i < profile_values.length; i++) {
total_words += profile_values[i].innerHTML.trim().split(' ').length;
}
document.getElementById('word-count').innerHTML = total_words;<div class="profile-value">
<td>
<p>I am a profile value</p>
</td>
</div>
<div id="stats">
<h3>Stats</h3>
<span id="word-count" class="large">0</span>
<br>words found.
</div>
发布于 2016-07-14 19:07:31
使用textContent而不是innerHTML,修剪() it,并使用正则表达式在任何(序列)空格(包括制表符、换行符、.不仅是空间):
total_words += profile_values[i].textContent.trim().split(/\s+/).length;
var profile_values = document.getElementsByClassName('profile-value');
var total_words = 0;
for (i = 0; i < profile_values.length; i++) {
total_words += profile_values[i].textContent.trim().split(/\s+/).length;
}
document.getElementById('word-count').innerHTML = total_words;<table><tr class="profile-value">
<td>
<p>I am a profile value</p>
</td>
</tr></table>
<div id="stats">
<h3>Stats</h3>
<span id="word-count" class="large">0</span>
<br>words found.
</div>
NB1:td标记不允许作为div的子标记。
NB2:在某些情况下,坚持使用innerHTML的解决方案会报告错误的号码,如本例所示:
<table><tr class="profile-value">
<td style="background: yellow">
<p>I am a <font color="red">profile </font> value</p>
</td>
</tr></table>使用innerHTML的解决方案将报告11个单词,而仍然只有5个单词。
发布于 2016-07-14 19:05:44
您只需要查找文本节点并提取这些节点,然后在没有分隔符的情况下将它们连接起来,然后运行您拥有的循环,从而剥离html。
https://stackoverflow.com/questions/38382252
复制相似问题