显示的部分的字数(使用:目标选择器)

时间:2018-01-27 20:17:52

标签: javascript html css

我有这个:

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;
}

我的问题是:如何使单词计数脚本目标(计数)仅显示所显示的部分,并且仅使用那些部分。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您可以将click事件附加到a元素,将this.hash从索引1传递到wordsCount(),然后使用RegExp {{1} }和/[^\s]+/g

&#13;
&#13;
String.prototype.match()
&#13;
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)))
  }
})
&#13;
section {
  display: none;
}

:target {
  display: block;
}

.words:before {
  content: "words: "
}

.words {
  margin-top: 10px;
  background-color: silver;
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您必须在锚标记的点击事件中找到单词的长度。

Stack Snippet

&#13;
&#13;
Numbers=[1,3,5,7]
for i in Numbers:
    if i%2==0:
        print(i)
    else: 
        i%2==1
    print(i)
for l in Numbers:
        if l>1 & i%l==1:
            print(l)
&#13;
var words = document.querySelector('.words');
var anchor = document.querySelectorAll("a");
var section = document.querySelectorAll("section");

for (let i = 0; i < anchor.length; i++) {
  anchor[i].addEventListener("click", function() {
    var arr = document.getElementById(i + 1).innerText.trim().replace(/\s+/g, ' ').split(' ');
    words.textContent = !arr[0] ? 0 : arr.length;
  })
}
&#13;
section {
  display: none;
}

:target {
  display: block;
}

.words:before {
  content: "words: "
}

.words {
  margin-top: 10px;
  background-color: silver;
}
&#13;
&#13;
&#13;