意外落入if语句

unexpected fall to if statement

本文关键字:语句 if 意外      更新时间:2023-09-26

HTML

<div id="main">
  <span>v</span>
  <div id="main_cursor"></div>
</div>

Javascript

function highlight_word() {
  var cursor = document.getElementById(area + '_cursor'),
    pe = cursor.previousElementSibling,
    ne = cursor.nextElementSibling;
  var word = [];
  f();
  word = word.join();
  if (isInArr(keywords_arr, word)) {
    f(true);
  };
  function f(p = false) {
    while ((pe === null ? " " : pe.innerHTML) !== " " ||
      (ne === null ? " " : ne.innerHTML) !== " ") {
      if (pe !== null) {
        while (pe.innerHTML !== " ") {
          p === true ? pe.style.color = "green" : word.push(pe.innerHTML);
          pe = pe.previousElementSibling;
        }; // end of while
        word = word.reverse();
      }; //end of if
      if (ne !== null) {
        while (ne.innerHTML !== " ") {
          p === true ? pe.style.color = "green" : word.push(ne.innerHTML);
          ne = ne.nextElementSibling;
        }; //end of while
      }; //end of if
    }; // end of while
  }; // end of function f
};

目标

目标是首先获取位于main_cursor和具有空格作为内部文本的跨度之间的所有跨度的内部文本,并检查单词获取是否存在于数组keywords_arr中。该单词是否存在于该数组中,然后更改文本的颜色所有这些跨度的

或者如果单词在keyword_arr 中,则仅突出显示

错误

未捕获的类型错误:无法读取空的属性"innerHTML"

错误显示在行中

while(pe.innerHTML!==" "){

并且只有当CCD_ 4的条件得到满足时才会发生这种情况,这是不应该发生的!


我该怎么办?

此循环内部

while (pe.innerHTML !== " ") {
  p === true ? pe.style.color = "green" : word.push(pe.innerHTML);
  pe = pe.previousElementSibling;
}; // end of while

您正在重新分配pe的值。如果pe不再有任何以前的同级,它将被分配给null

相反,您可以将条件更改为这样,以确保pe在检查其innerHTML:之前有效

while (pe && pe.innerHTML !== " ") {