猿问

无法读取 JavaScript 中未定义的属性“textContent”

问题是什么?我声明了变量 n


var n = 0;


while (true) {

  var comment = document.getElementsByClassName('wall_reply_text')[n].textContent;

  

  if (comment.indexOf("публикации") == 0) {

    alert(comment);

  }

  

  n++;

}


繁星点点滴滴
浏览 92回答 2
2回答

一只萌萌小番薯

wall_reply_text最可能的解释是当这段代码运行时没有类名的元素,所以document.getElementsByClassName('wall_reply_text')返回一个空数组。当您尝试访问该空数组中的索引 0 时,您会得到undefined,因此在尝试访问时会出现错误undefined.textContent。

慕桂英4014372

如果没有元素,则需要中断var n = 0, comment=""while (true) {&nbsp; const div = document.getElementsByClassName('wall_reply_text')[n]&nbsp; if (div) comment = div.textContent;&nbsp; else break&nbsp;&nbsp;&nbsp; if (comment.indexOf("публикации") == 0) {&nbsp; &nbsp; console.log(n,comment);&nbsp; }&nbsp;&nbsp;&nbsp; n++;}<div class="wall_reply_text">1</div><div class="wall_reply_text">публикации</div><div class="wall_reply_text">3</div><div class="wall_reply_text">4</div>这是一种更优雅的方式[...document.querySelectorAll('.wall_reply_text')]&nbsp; .map(div => div.textContent)&nbsp; .forEach((comment,i) => {&nbsp; &nbsp; if (comment.indexOf("публикации") == 0) {&nbsp; &nbsp; &nbsp; console.log(i,comment);&nbsp; &nbsp; }})<div class="wall_reply_text">1</div><div class="wall_reply_text">публикации</div><div class="wall_reply_text">3</div><div class="wall_reply_text">публикации</div>如果您只需要一个索引,则可以选择const comments = [...document.querySelectorAll('.wall_reply_text')]&nbsp; .map(div => div.textContent)console.log(comments.indexOf("публикации"))<div class="wall_reply_text">1</div><div class="wall_reply_text">публикации</div><div class="wall_reply_text">3</div><div class="wall_reply_text">4</div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答