我试图弄清楚为什么我的函数中出现未定义的错误。
我想做的是使用分割和数组从input1
到input2
逐个显示每个单词。
当按下按钮时它将起作用,并且文本从input1
到input2
循环良好。
但是,如果文本被删除或添加到input1
中,它将返回未定义的文本。
var tagChanger = null,
tagLength = 0,
tagMaxLength = 0;
function changer() {
clearInterval(tagChanger);
if (tagChanger !== null) {
tagChanger = null;
} else {
tagChanger = setInterval(function() {
var tag = document.getElementById('input1').value,
Name = tag.split(" ")[tagLength];
document.getElementById('input2').value = Name;
tagMaxLength = tag.split(" ").length - 1;
if (tagMaxLength == tagLength) {
tagLength = 0;
} else {
tagLength++;
}
}, 500);
}
}
var button = document.getElementById("button");
button.addEventListener("click", changer);
input 1: <input type="text" id="input1" value="I HOPE SOMEONE CAN HELP ME FIX THIS">
<br><br> input 2: <input type="text" id="input2">
<br>
<br>
<button id="button" style="width: 30%;">BUTTON</button>
答案 0 :(得分:0)
如果Name
变量具有值,则您添加了tag
变量而未检入。这就是您的情况
var tagChanger = null,
tagLength = 0,
tagMaxLength = 0;
function changer() {
clearInterval(tagChanger);
if (tagChanger !== null) {
console.log("hi")
tagChanger = null;
} else {
tagChanger = setInterval(function() {
var tag = document.getElementById('input1').value
if(tag != ''){
var Name = tag.split(" ")[tagLength];
document.getElementById('input2').value = Name;
tagMaxLength = tag.split(" ").length - 1;
if (tagMaxLength == tagLength) {
tagLength = 0;
} else {
tagLength++;
}
} else{
tagLength = 0;
document.getElementById('input2').value =""
}
}, 500);
}
}
var button = document.getElementById("button");
button.addEventListener("click", changer);
input 1: <input type="text" id="input1" value="I HOPE SOMEONE CAN HELP ME FIX THIS">
<br><br> input 2: <input type="text" id="input2">
<br>
<br>
<button id="button" style="width: 30%;">BUTTON</button>
答案 1 :(得分:0)
只需添加一个foreach循环,然后通过setTimeout
函数(如
function changer() {
var tag = document.getElementById('input1').value
var Name = tag.split(" ");
Name.forEach((sr, index) => {
setTimeout(() => document.getElementById("input2").value = sr, 500 * index);
});
}
var button = document.getElementById("button");
button.addEventListener("click", changer);
input 1: <input type="text" id="input1" value="DONT WORRY, THE HELP HAS ARRIVED">
<br><br> input 2: <input type="text" id="input2">
<br>
<br>
<button id="button" style="width: 30%;">BUTTON</button>
另外,继续通过索引增加循环的持续时间,并根据您的方便更改值