将按钮添加到已使用innerHTML的div

时间:2018-04-15 08:55:00

标签: javascript jquery

我正在尝试使用JS显示测验的分数,并给它一个完成按钮,将数据发送到数据库并返回到另一个页面。我可以显示分数测试而不是按钮

<div class="container" id="quiz">
<h1>Quiz</h1>
<div class="quiz material-main">
  <h3 id="questions" ></h3>
  <div id= "audios" ></div>
  <div id="images" ></div>
        <div id="choices" ></div>
  <div class="quizBtn">
        <br />
            <button id="backBtn" class="backBtn" style="font-family: sans-serif; font-size: 22px; background-color: #279; color: #fff; border: 0px; border-radius: 3px; padding: 20px; cursor: pointer; margin-bottom: 20px;">Back</button>
    <button id="nextBtn" class="nextBtn" style="font-family: sans-serif; font-size: 22px; background-color: #279; color: #fff; border: 0px; border-radius: 3px; padding: 20px; cursor: pointer; margin-bottom: 20px;">Next</button>
        </div>
</div>
<div class="complete"></div>
</div>

JS:

if (counter >= data.length) {
           var score = Math.round(numCorrect/data.length*100);
          $('.quiz').hide().fadeIn("slow");
          document.getElementById('quiz').innerHTML="Quiz Complete! You scored " + numCorrect + " out of " + counter;
          document.getElementById('quiz').appendChild('<button id="complete" class="nextBtn" style="font-family: sans-serif; font-size: 22px; background-color: #279; color: #fff; border: 0px; border-radius: 3px; padding: 20px; cursor: pointer; margin-bottom: 20px;">Complete</button>')
          return score; // returns false *(there has to be a better way! figure it out.)*
        }

2 个答案:

答案 0 :(得分:1)

appendChild()用于节点,您可以再次使用innerHTML

尝试:

document.getElementById('quiz').innerHTML += '<button id="complete" class="nextBtn" style="font-family: sans-serif; font-size: 22px; background-color: #279; color: #fff; border: 0px; border-radius: 3px; padding: 20px; cursor: pointer; margin-bottom: 20px;">Complete</button>';

不要忘记;

答案 1 :(得分:0)

  1. 尝试innerHTML +=,请小心使用append,因为IE不支持它:
  2. document.getElementById('quiz').innerHTML += ('<button id="complete" class="nextBtn" style="font-family: sans-serif; font-size: 22px; background-color: #279; color: #fff; border: 0px; border-radius: 3px; padding: 20px; cursor: pointer; margin-bottom: 20px;">Complete</button>')

    1. 尝试使用局部变量来提高代码的速度:
    2. var el = document.getElementById('quiz');
      el.innerHTML = 'sth';
      el.innerHTML += 'another sth';