我正在学习 JavaScript,但我不明白为什么字数统计功能没有检索到我的消息。当我单击包含多个单词的消息的按钮时,我收到的字数为“1”,这是不正确的。我已经测试了 calWords 函数,该函数在使用 console.log(calWords(some message)); 时可以正常工作。 此代码是根据要求编写的,我无法使用 .split() 或 正则表达式。这是代码的链接: https://jsbin.com/rucicol/edit?html,js,console,output
<form class="userform">
<label id="labeltxt">Enter a Message to Display Statistics</label><br>
<textarea type="text" name="message" id='userInput'></textarea><br>
<button type="button" onclick="showStats()">Submit</button>
</form>
// global variables
var numWords = 0;
var displayStats = document.getElementById('userInput').value;
// display stats
function showStats() {
alert(calWords(displayStats));
}
// calculate words
function calWords(str) {
for(var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
numWords ++;
}
}
return numWords + 1;
}
最佳答案
这是因为,当您创建 displayStats
时,您会获取创建时 textarea
的值(例如,什么也没有)。
为了使您的脚本正常工作,您可以在 displayStats
中“存储”对 textarea
的引用,并在需要时访问他的值
。
这是更正后的脚本:
// global variables
var numWords = 0;
var displayStats = document.getElementById('userInput');
// display stats
function showStats()
alert(calWords(displayStats.value));
}
// calculate words
function calWords(str) {
for(var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
numWords ++;
}
}
return numWords + 1;
}
关于JavaScript 函数无法从 HTML 文本区域检索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45230002/