首页 > 解决方案 > 为什么我的单词计数器没有返回任何内容?

问题描述

我制作了一个简单的单词计数器来计算 HTML 文本框中的单词数。它从 html 文档中的 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">

标签: javascripthtmlword-count

解决方案


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, '').replace(/\s+/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">


推荐阅读