我有这个:
var editor = document.getElementById('editor');
var words = document.querySelector('.words');
function wordsCount() {
var arr = editor.innerText.trim().replace(/\s+/g, ' ').split(' ');
words.textContent = !arr[0] ? 0 : arr.length;
}
wordsCount();
section {
display: none;
}
:target {
display: block;
}
.words:before {
content: "words: "
}
.words {
margin-top: 10px;
background-color: silver;
}
<aside>
<ol>
<li><a href="#1">Show 1</a></li>
<li><a href="#2">Show 2</a></li>
<li><a href="#3">Show 3</a></li>
</ol>
</aside>
<div id="editor">
<section id="1">Section 1 text</section>
<section id="2">Section 2 text</section>
<section id="3">Section 3 text</section>
</div>
<div class="words"></div>
注意:现在,要使字数统计正常工作,我需要删除:
section {
display: none;
}
我的问题是:如何使字数统计脚本目标(仅计数)所显示的部分,并且仅对这些部分进行计数。有任何想法吗?
最佳答案
您可以将click
事件附加到a
元素,将this.hash
从索引1
传递到wordsCount()
,使用RegExp
/[^\s]+/g
和String.prototype.match()
var editor = document.getElementById('editor');
var words = document.querySelector('.words');
function wordsCount(el) {
var arr = el.textContent.trim().match(/[^\s]+/g);
words.textContent = !arr[0] ? 0 : arr.length;
}
document.querySelectorAll("a")
.forEach(function(el) {
el.onclick = function() {
wordsCount(document.getElementById(this.hash.slice(1)))
}
})
section {
display: none;
}
:target {
display: block;
}
.words:before {
content: "words: "
}
.words {
margin-top: 10px;
background-color: silver;
}
<aside>
<ol>
<li><a href="#1">Show 1</a></li>
<li><a href="#2">Show 2</a></li>
<li><a href="#3">Show 3</a></li>
</ol>
</aside>
<div id="editor">
<section id="1">Section 1 text a</section>
<section id="2">Section 2 text b c</section>
<section id="3">Section 3 text d e f</section>
</div>
<div class="words"></div>