函数返回未定义

时间:2019-04-26 04:52:09

标签: javascript

我试图弄清楚为什么我的函数中出现未定义的错误。

我想做的是使用分割和数组从input1input2逐个显示每个单词。

当按下按钮时它将起作用,并且文本从input1input2循环良好。

但是,如果文本被删除或添加到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: &nbsp; <input type="text" id="input1" value="I HOPE SOMEONE CAN HELP ME FIX THIS">
<br><br> input 2: &nbsp; <input type="text" id="input2">
<br>
<br>
<button id="button" style="width: 30%;">BUTTON</button>

2 个答案:

答案 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: &nbsp; <input type="text" id="input1" value="I HOPE SOMEONE CAN HELP ME FIX THIS">
<br><br> input 2: &nbsp; <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: &nbsp; <input type="text" id="input1" value="DONT WORRY, THE HELP HAS ARRIVED">
<br><br> input 2: &nbsp; <input type="text" id="input2">
<br>
<br>
<button id="button" style="width: 30%;">BUTTON</button>


另外,继续通过索引增加循环的持续时间,并根据您的方便更改值