试图让JS使用数组替换innerHTML内容进行文本冒险

Posted

技术标签:

【中文标题】试图让JS使用数组替换innerHTML内容进行文本冒险【英文标题】:Trying to get JS to replace innerHTML content using an array for text adventure 【发布时间】:2020-01-11 15:43:56 【问题描述】:

我正在尝试使用 javascript 创建一个非常小的文本冒险。第一个“页面”包含一个表单,用于在 div 中输入信息,我想在用户每次按下“下一步”时替换 div 中的信息。

代码:

let name = [],
  age = [],
  place = [],
  verb = [];

document.getElementByID('story');

function nextPage() 
  let i = 0;
  i < showInfo.length;
  i++;


  let story = document.getElementById('story');
  let story.innerhtml = showInfo;
  let showInfo = [page1, page2, page3];
  let page1 = `Div replacement content 1`;
  let page2 = `Div replacement content 2`;
  let page3 = `Div replacement content 3`;
input[type="text"] 
  width: 100px;
<div id="story">
  <form>
    <h2>Start Your Adventure!</h2>
    <h3>Who are you?</h3>
    <p>Name: <input type="text" name="name" placeholder="Jessica"></p>
    <p>Age: <input type="text" name="age" placeholder="twenty"></p>
    <p>Hometown:<br>
      <input type="radio" name="place" id="Portland">Portland<br>
      <input type="radio" name="place" id="Vancouver">Vancouver<br></p>
    <p>Favorite activity:<br>
      <input type="radio" name="verb" id="swimming">Swimming<br>
      <input type="radio" name="verb" id="running">Running<br>
      <input type="radio" name="verb" id="cooking">Cooking<br></p>
  </form>
</div>
<button onclick="nextPage()">Next</button>

【问题讨论】:

您的代码中有很多语法错误:有两个let story 声明;您在初始化变量之前访问变量showInfo;在初始化它们之前,您正在访问 page1page2page3getElementByID 不存在,一定是getElementById 注意区分大小写 【参考方案1】:

您非常接近,主要问题在于变量的顺序,以及您必须跟踪每次点击时所在的页面:

let name = [],
  age = [],
  place = [],
  verb = [],
  curPage = 0;



function nextPage() 
  let page1 = `Div replacement content 1`;
  let page2 = `Div replacement content 2`;
  let page3 = `Div replacement content 3`;
  let showInfo = [page1, page2, page3];

  let story = document.getElementById('story');
  story.innerHTML = showInfo[curPage];
  if (curPage < 2) 
    curPage++;
  

input[type="text"] 
  width: 100px;
<div id="story">
  <form>
    <h2>Start Your Adventure!</h2>
    <h3>Who are you?</h3>
    <p>Name: <input type="text" name="name" placeholder="Jessica"></p>
    <p>Age: <input type="text" name="age" placeholder="twenty"></p>
    <p>Hometown:<br>
      <input type="radio" name="place" id="Portland">Portland<br>
      <input type="radio" name="place" id="Vancouver">Vancouver<br></p>
    <p>Favorite activity:<br>
      <input type="radio" name="verb" id="swimming">Swimming<br>
      <input type="radio" name="verb" id="running">Running<br>
      <input type="radio" name="verb" id="cooking">Cooking<br></p>
  </form>
</div>
<button onclick="nextPage()">Next</button>

【讨论】:

以上是关于试图让JS使用数组替换innerHTML内容进行文本冒险的主要内容,如果未能解决你的问题,请参考以下文章

js怎样清除或者替换添加的标签

在Angular中替换innerHTML不必要地关闭标签[重复]

用其 innerHTML 替换锚点

js 替换 innerHTML 仅适用于没有 jQuery

js基础

jQuery:延迟替换 div 的 innerHTML?