如何解决为什么我的文字计数器不返回任何内容?
我做了一个简单的单词计数器来计算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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。