在网页中有一个textarea(id =“text”)和一个按钮(id =“dlButton3”)。
我要做的是将文本输入textarea。当我按下按钮时,将发生以下情况:
问题是,通过以下代码,我可以从文本区域获取字符串,但是知道为什么我不能拆分字符串,并且它返回错误“Uncaught ReferenceError:targetString is not defined”
代码如下
function findlongestword(){
var testing = document.getElementById('text').value;
console.log(testing);
var strText = testing.split(" ");
var length = 0;
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function(){
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}
错误是什么? 非常感谢您的帮助!
答案 0 :(得分:0)
详细了解块范围 targetString仅存在于循环
中function findlongestword() {
var testing = document.getElementById('text').value;
var strText = testing.split(" ");
var length = 0;
var targetString = '';
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function() {
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}
答案 1 :(得分:0)
&#34;未捕获的ReferenceError:未定义targetString&#34; 在循环中使用之前,您没有声明targetString。因此,javascript不知道在哪里可以找到或者推荐&#39;在循环结束后到它。
添加var targetString =&#34;&#34 ;;在循环开始之前,问题将得到解决。
function findlongestword(){
var testing = document.getElementById('text').value;
console.log(testing);
var strText = testing.split(" ");
//ADD HERE
var targetString = "";
var length = 0;
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function(){
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}