为什么我的文字计数器不返回任何内容?

问题描述

我做了一个简单的单词计数器来计算HTML文本框中的单词数。它从html doc的inputText字段中获取数据,并计算其中有多少个实际单词。我无法在框中显示字数统计。我在做什么错了?

function count_words(evt) {
    var input = document.getElementById('inputText').value;
    var words = 0;
    input = count_words().replace(/(< ([^>]+)<)/g,'').replace(/\s+/g,' ');
    input = input.replace(/^\s\s*/,'').replace(/\s\s*$/,'');
    words = input.split(' ').length;

    words = document.getElementById('numberOfWords').innerHTML;
}

window.onload = function (evt) {
    if (document && document.getElementById) {
        document.getElementById('btnConvert').onclick = count_words;
    }
}
<textarea id="inputText" cols="30" rows="6">The quick brown fox jumps over the lazy dog.</textarea>
<br>
<input type="button" id="btnConvert" value="Word Count">
<input id="numberOfWords" type="text" value="" size="6">

解决方法

words = document.getElementById('numberOfWords').innerHTML;

这部分是错误的。这意味着您正在将innerHTML属性值分配给words值。

现在,您正在将值插入input标签,因此需要将words值分配给value属性。

document.getElementById('numberOfWords').value = words;
input = count_words().replace(/(< ([^>]+)<)/g,'').replace(/\s+/g,' ');

这部分是错误的。 count_words()应替换为input

function count_words(evt) {
    var input = document.getElementById('inputText').value;
    var words = 0;
    input = input.replace(/(< ([^>]+)<)/g,' ');
    input = input.replace(/^\s\s*/,'').replace(/\s\s*$/,'');
    words = input.split(' ').length;

    document.getElementById('numberOfWords').value = words;
}

window.onload = function (evt) {
    if (document && document.getElementById) {
        document.getElementById('btnConvert').onclick = count_words;
    }
}
<textarea id="inputText" cols="30" rows="6">The quick brown fox jumps over the lazy dog.</textarea>
<br>
<input type="button" id="btnConvert" value="Word Count">
<input id="numberOfWords" type="text" value="" size="6">

,

对功能的少量修改应该可以解决

  function count_words(evt) {
    var input = document.getElementById('inputText').value;
    var words = 0;
    input = input.replace(/(< ([^>]+)<)/g,' ');
    words = input.split(' ').length;
    document.getElementById('numberOfWords').value = words; 
}
,

我知道了,只需将count_words().replace更改为input.replace,将words = document.getElementById('numberOfWords').innerHTML更改为 document.getElementById('numberOfWords').innerText = words

function count_words(evt) {
    var input = document.getElementById('inputText').value;
    var words = 0;
    input = input.replace(/(< ([^>]+)<)/g,'');
    words = input.split(' ').length;

    document.getElementById('numberOfWords').value = words;
}

window.onload = function (evt) {
    if (document && document.getElementById) {
        document.getElementById('btnConvert').onclick = count_words;
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...