javascript - 未捕获的类型错误 : Cannot read property 'firstElementChild' of null

标签 javascript jquery html css

正在尝试执行代码。

程序:

点击任意选项 --> 点击No, I am not sure --> 点击任意选项 --> 点击Yes, lock the option

第二次按钮(是的,锁定选项)不会做任何事情,在控制台中我发现:

Uncaught TypeError: Cannot read property 'firstElementChild' of null

.correct {
  display: flex;
  align-items: center;
  width: 90%;
  height: auto;
  min-height: 40px;
  position: relative;
  background: green;
  color: white;
}

.correct::after {
  content: "";
  position: absolute;
  left: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-right: 20px solid green;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.correct::before {
  content: "";
  position: absolute;
  right: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-left: 20px solid green;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.lifeline {
  background-color: pink;
  color: white;
}

.incorrect {
  display: flex;
  align-items: center;
  width: 90%;
  height: auto;
  min-height: 40px;
  position: relative;
  background: red;
  color: white;
}

.incorrect::after {
  content: "";
  position: absolute;
  left: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-right: 20px solid red;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.incorrect::before {
  content: "";
  position: absolute;
  right: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-left: 20px solid red;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.locked {
  display: flex;
  align-items: center;
  width: 90%;
  height: auto;
  min-height: 40px;
  position: relative;
  background: yellow;
  color: white;
}

.locked::after {
  content: "";
  position: absolute;
  left: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-right: 20px solid yellow;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.locked::before {
  content: "";
  position: absolute;
  right: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-left: 20px solid yellow;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.timeout {
  background-color: orange;
  color: white;
}


/*
.question1{
	background-color: blue;
	color: white;
}
*/

.hidden_timer {
  visibility: hidden;
  display: none;
}

.visible {
  visibility: visible !important
}

.timeout {
  display: flex;
  align-items: center;
  width: 90%;
  height: auto;
  min-height: 40px;
  position: relative;
  background: orange;
  color: white;
}

.timeout::after {
  content: "";
  position: absolute;
  left: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-right: 20px solid orange;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.timeout::before {
  content: "";
  position: absolute;
  right: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-left: 20px solid orange;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.question1 {
  display: flex;
  align-items: center;
  width: 90%;
  height: auto;
  min-height: 40px;
  position: relative;
  background: blue;
  color: white;
}

.question1::after {
  content: "";
  position: absolute;
  left: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-right: 20px solid blue;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.question1::before {
  content: "";
  position: absolute;
  right: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-left: 20px solid blue;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
}

.table_cstm {
  border-collapse: separate;
  border-spacing: 15;
  /* Apply cell spacing */
  table-layout: fixed
}

td:last-child div {
  margin-left: auto;
}


/* Play header starts */

.button_cstm_quit {
  background-color: red;
  border: none;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 35px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 50%;
}

.button_cstm_quit:hover {
  color: red;
  font-weight: bold;
  background: none;
  border: 2px solid red;
}

.button_cstm_ll {
  background-color: blue;
  border: none;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 35px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 50%;
  position: relative;
}

.button_cstm_ll:hover {
  color: blue;
  font-weight: bold;
  background: none;
  border: 2px solid blue;
}

.button_cst_pnts {
  background-color: orange;
  border: none;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 35px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 50%;
  position: relative;
}

.button_cst_pnt:hover {
  color: orange;
  font-weight: bold;
  background: none;
  border: 2px solid orange;
}

.button_cstm_nxt {
  background-color: blue;
  border: none;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 35px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 50%;
  position: relative;
}

.button_cstm_nxt:hover {
  color: blue;
  font-weight: bold;
  background: none;
  border: 2px solid blue;
}

.button_cstm_time {
  background-color: #FF8C00;
  border: none;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 35px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 50%;
}

.button_cstm_time:hover {
  color: #FF8C00;
  font-weight: bold;
  background: none;
  border: 2px solid #FF8C00;
}

#container_cstm {
  width: 100%;
}

#left_cstm {
  float: left;
  width: 100px;
}

#right_cstm {
  float: right;
  width: 100px;
}

#center_cstm {
  margin: 0 auto;
  width: 100px;
}

#play_head {
  display: flex;
  /* establish flex container */
  flex-direction: row;
  /* default value; can be omitted */
  flex-wrap: nowrap;
  /* default value; can be omitted */
  justify-content: space-between;
  /* switched from default (flex-start, see below) */
}

.red_cross:before,
.red_cross:after {
  position: absolute;
  content: '';
  top: -5px;
  bottom: -5px;
  width: 5px;
  background: #ff0000;
  left: 0;
  right: 0;
  margin: 0 auto;
}

.red_cross:before {
  transform: skew(30deg);
}

.red_cross:after {
  transform: skew(-30deg);
}

.disp_none {
  display: none;
}


/* Play header ends */
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="http://localhost/bol25kids/style/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<body onload="startTest()">

  <div id="play_head">

    <div>

      <!-- Modal -->
      <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">

          <!-- Modal content-->
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title" id="m_q"></h4>
            </div>
            <div class="modal-body">
              <p id="m_o"></p>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-danger btn-lg" id="myBtnC">No, I am not sure</button>
              <button type="button" class="btn btn-info btn-lg" id="myBtnO">Yes, Lock the Option</button>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>


  <div class="container">
    <table id="test" class="table table-responsive table_cstm" cellspacing="100">
      <!--<tr>
<td colspan="2" id="timer"></td>
</tr>-->
    </table>


    <script>
      var questions = [{
        questionId: "question1",
        answerId: "A",
        question: "3) आत्मा के साथ दूध - पानी की तरह एकीभूत होने वाला कर्म -पुद्गल समूह कोनसा है  ?(A198206)",
        options: ["A)", "B)", "C)", "D)"],
        option_text: ["बंध", "पुण्य ", "पाप", "आश्रव "],
        answer: "A)",
        locked: false
      }];

      var table = document.getElementById("test");
      var row = table.insertRow(0);
      var cell1 = row.insertCell(0);
      cell1.colSpan = 2;
      row.className = 'hidden_timer';
      row.id = 'timer';

      var i = 0;
      var o = 1;
      var p = 2;

      function generateQuestion(question) {
        // noinspection JSAnnotator
        i += 1;
        o += 2;
        p += 3;
        var newQuestion = `
        
            <td colspan="2"><div class="question1" style="justify-content: center; width: 100%;">${question.question}`;
        var display_options_1 = `
	
            <td><span onclick="onSelect(event)" class="${question.questionId}" id="A${p}"><span id="A${i}" >${question.options[0]}</span><span id="A${o}" > ${question.option_text[0]}</span></span></td>
            <td><span onclick="onSelect(event)" class="${question.questionId}" id="B${p}"><span id="B${i}"  >${question.options[1]}</span><span id="B${o}" > ${question.option_text[1]}</span></span></td>
		`;
        var display_options_2 = `
	
            <td><span onclick="onSelect(event)" class="${question.questionId}" id="C${p}"><span id="C${i}"  >${question.options[2]}</span><span id="C${o}" > ${question.option_text[2]}</span></span></td>
            <td><span onclick="onSelect(event)" class="${question.questionId}" id="D${p}"><span id="D${i}"  >${question.options[3]}</span><span id="D${o}" > ${question.option_text[3]}</span></span></td>
		`;
        var row2 = table.insertRow(1);
        row2.innerHTML = newQuestion;

        var row3 = table.insertRow(2);
        setTimeout(() => {
          row3.innerHTML = display_options_1;
        }, 2000);
        var row4 = table.insertRow(3);
        setTimeout(function() {
          row4.innerHTML = display_options_2;
        }, 2000);
      }




      function onSelect(e) {
        var selection = e.currentTarget;
        var questionId = e.currentTarget.className;
        var currentQuestion = questions.find(function(q) {
          return q.questionId == questionId
        });
        $("#myModal").modal();
        document.getElementById("m_q").innerHTML = "<h3>" + currentQuestion.question + "</h3>";
        document.getElementById("m_o").innerHTML = "<h2>" + selection.firstElementChild.innerText + "</h2>";

        $("#myBtnC").click(function() {
          //onConfirm(e);
          selection.setAttribute('class', 'question1');
          selection = null;
          $('#myModal').modal('hide');
        });

        $("#myBtnO").click(function() {

          if (currentQuestion.locked) {
            alert("Question already answered");
          } else if (currentQuestion.answer === selection.firstElementChild.innerText) {
            alert("Correct!!!");
          } else {
            alert("Incorrect...");
          }
          //generateQuestion(questions[i]);


          $('#myModal').modal('hide');
        });

      }


      function startTest() {
        generateQuestion(questions[i]);
      }
    </script>
</body>

JSFiddle

最佳答案

您的代码中几乎没有问题。一种是使用 selection 变量,您需要从 onSelect 函数中声明它。 另一个是每次调用 onSelect() 函数时都将 jQuery.click() 事件绑定(bind)到按钮。 尝试将事件处理程序放在函数之外,以及选择变量声明

 var selection;
 var currentQuestion;

function onSelect(e) {
  selection = e.currentTarget;
  var questionId = e.currentTarget.className;
  currentQuestion = questions.find(function(q) {
    return q.questionId == questionId
  }); 
   $("#myModal").modal();
   document.getElementById("m_q").innerHTML = "<h3>" + currentQuestion.question + "</h3>";
   document.getElementById("m_o").innerHTML = "<h2>" + selection.firstElementChild.innerText + "</h2>";



}
     $("#myBtnC").click(function(){
        //onConfirm(e);

        selection.setAttribute('class', 'question1');
        selection = null;
        $('#myModal').modal('hide');
    });

    $("#myBtnO").click(function(){

        if (currentQuestion.locked) {
  alert("Question already answered");
  } 
  else if (currentQuestion.answer === selection.firstElementChild.innerText) {
      alert("Correct!!!");
  } else {
    alert("Incorrect...");
  }
  //generateQuestion(questions[i]);


        $('#myModal').modal('hide');
    });

关于javascript - 未捕获的类型错误 : Cannot read property 'firstElementChild' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51251700/

相关文章:

html - 摆脱-webkit-padding-start : 40px

html - 如何在 CSS 中将左侧 float 元素居中?

javascript - Javascript 数组中偶数的总和?

javascript - 使用 React 聚焦 div 元素

jQuery 选择元素是否有特定内容

javascript - jQuery Toggle Slide 在 Safari 中不起作用

javascript - 在 bootstrap 多选下拉菜单上创建工具提示

javascript - 在模式中重复使用谷歌地图街景

javascript - 背景图像缩放

javascript - 有没有办法重新生成 link_to_add_association(特别是数据关联插入模板)?