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

更新控制 html 的变量时无法读取未定义错误的属性“添加”

更新控制 html 的变量时无法读取未定义错误的属性“添加”

qq_笑_17 2022-06-09 11:08:07
我使用数字作为元素 id,在 js 中由 i 表示,一旦按下开始按钮,它应该隐藏标题屏幕,更新 i,然后从新的 i 元素中删除隐藏类(隐藏元素)(问题1)和菜单栏元素。问题 1 和菜单栏应留在屏幕上。但是,菜单栏加载,但问题没有,并弹出错误。无法读取未定义的属性“添加”// variablesvar i = 0;var id = document.getElementById(i.toString());var next = document.getElementById("next");// hiding menu and other screensmenuBar.classList.add('hide');next.classList.add('hide');document.getElementById("1").setAttribute("class", "hide");document.getElementById("2").setAttribute("class", "hide");document.getElementById("3").setAttribute("class", "hide");document.getElementById("4").setAttribute("class", "hide");document.getElementById("5").setAttribute("class", "hide");// show the next screen when the next button is pressedfunction nextScreen() {  id.classList.add('hide');  if (i == 0) {    menuBar.classList.remove('hide');  }  i ++;    next.classlist.add('hide');  id.classList.remove('hide');}start.onclick = nextScreen;next.onclick = nextScreen;    <div class="container">      <!-- title screen -->      <div id='0' class='title'>        <h1>          Welcome to<br>the<br><strong>IMPOSSIBLE QUIZ</strong>        </h1>        <button id='start' class='green button'>          START        </button>      </div>            <!-- question 1 -->      <div id='1' class='question'>        <span class='questionIndicator'>          Question 1        </span>        <br>        <h2>          What is after        </h2>        <button id='secretAnswer' class='secret'>          ...?        </button>        <button id='q1WrongAnswer' class='answer button'>          this?        </button>        <button id='q1WrongAnswer' class='answer button'>          the answer        </button>        <button id='q1WrongAnswer' class='answer button'>          no idea        </button>      </div>
查看完整描述

1 回答

?
30秒到达战场

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

ID 为 2-5 的元素尚不存在,因此您无法调用setAttribute()它们。

另外,next.classlist.add('hide')应该是next.classList.add('hide')(camelCase)


查看完整回答
反对 回复 2022-06-09
  • 1 回答
  • 0 关注
  • 213 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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