无法从html文本框获取实时字数

时间:2015-12-03 03:00:29

标签: javascript html

我是html和javascript的新手。我有一个文本框,我正在尝试计算单词的数量,然后实时显示计数。我不明白我在这方面做错了什么,或者如何纠正它。 textContent对我没有多大意义。

<html>
  <head>
    <style>
      input[type='text'] {width:50px;}
      textarea {width:500px;height:300px;}
    </style>
  </head>
  <body>
  <div>
    <h2>Test</h2>
    <p>The number of words is <span id="wordCount"></span></p>
    <textarea id="toCount"></textarea>
  </div>
      <script>

    document.getElementById('toCount').addEventListener('input', function () {
        var text = this.textContent,

        count = text.trim().replace(/\s+/g, ' ').split(' ').length;

        document.querySelector('.wordCount').textContent = count;

    });
    </script>
  </body>
</html>

我现在得到的错误是 Uncaught TypeError: Cannot set property 'textContent' of null

4 个答案:

答案 0 :(得分:1)

您获得null的原因是:在选择中,#wordCount是Id,而.wordCount是按类。所以document.querySelector('.wordCount')返回null,因为没有类wordCount的元素。

修复只是改变

document.querySelector('.wordCount').textContent = count;

document.querySelector('#wordCount').textContent = count;

答案 1 :(得分:1)

您的选择器应为#wordCount,并且可以使用值

访问textarea内容
.vue

答案 2 :(得分:0)

试试这个。

 document.getElementById('toCount').addEventListener('input', function () {
        var text = this.value,

        count = text.trim().split(' ').length;

        document.querySelector('#wordCount').textContent = count;

    });

以下是jsfiddle

答案 3 :(得分:0)

试试这个。

    document.getElementById('toCount').addEventListener('input', function () {
       // var text = this.textContent,
        var text = this.value,

        count = text.trim().replace(/\s+/g, ' ').split(' ').length;

       // document.querySelector('#wordCount').textContent = count;
      document.querySelector('#wordCount').textContent = count;

    });