为了账号安全,请及时绑定邮箱和手机立即绑定

函数返回未定义

函数返回未定义

拉丁的传说 2021-05-04 15:49:43
我试图弄清楚为什么我的函数中出现未定义的错误。我想做的是从逐个显示每个单词,input1直到input2使用split和array。当按下该按钮时,它将起作用,并且文本从input1到可以循环显示input2。但是,如果删除或添加了文本,input1则返回undefined。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 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

只需添加一个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>

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


查看完整回答
反对 回复 2021-05-13
?
BIG阳

TA贡献1859条经验 获得超6个赞

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>


查看完整回答
反对 回复 2021-05-13
  • 2 回答
  • 0 关注
  • 258 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号