javascript - 为什么我的单词计数器没有返回任何内容?
问题描述
我制作了一个简单的单词计数器来计算 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">
解决方案
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">
推荐阅读
- angular - Angular 4 - 获取 IIS 错误 404 页面,而不是根据用户权限重定向到我的 404 页面
- visual-studio - 当我没有更改任何内容时,为什么 TFS 会显示我所有文件的挂起更改?
- python - 返回数字的最大因子非常慢
- orcid - 使用 ORCID API 获取一个人的 ORCID
- c# - 将字符串解析为 DateTime 时,先解析字符串以获取数据,然后再将每个变量放入 DateTime 对象中
- python - 如何追溯保存扩展的 Django 模型?
- c# - Xml - '=' 是一个意外的标记,预期的标记是 ';'
- python - 二和 LeetCode - 为什么我自己的代码失败了
- mysql - 在一个文件中编写多个 MySQL(在 vsCode 中)查询。如何避免不断写“USE DBaseName”?
- charts - 如何在颤振、x 轴和 y 轴上为图表添加名称?