简体   繁体   English

试图获取span元素的内部文本内容

[英]trying to get the inner text content of a span element

I'm trying to create a search bar that will allow the user to search an array of items. 我正在尝试创建一个搜索栏,以允许用户搜索一系列项目。 I'm using a span element as my filter, but for some reason, I can't get the contents of the element to assign to a variable. 我正在使用span元素作为过滤器,但是由于某些原因,我无法获取要分配给变量的元素内容。

It's a pretty straight forward setup. 这是一个非常简单的设置。

I grab the contents of the class wrapping the list, then grab each span element. 我抓取包装列表的类的内容,然后抓取每个span元素。 For sanity reasons I console.log the span elements to ensure they are captured (which, they are). 出于理智的考虑,我会在console.log中记录span元素,以确保它们被捕获。

I then attempt to grab the text contents within and assign it to a txtValue variable which I would then proceed to do a comparison check with the filter. 然后,我尝试获取其中的文本内容,并将其分配给txtValue变量,然后继续对过滤器进行比较检查。

The part where I assign it to a text value is where the bug occurs, it doesn't seem to grab the inner text. 我将其分配给文本值的部分是发生错误的地方,它似乎没有抓住内部文本。 Perhaps I'm going about this wrong? 也许我要解决这个错误?

 function search() { var input, filter, e, content, txtValue; input = document.getElementById("search"); filter = input.value.toUpperCase(); e = document.getElementById("search-list"); content = e.getElementsByTagName("span"); console.log(content); for (i = 0; i < content.length; i++) { if (content) { txtValue = content.innerHTML; console.log(textValue); if (txtValue.toUpperCase().indexOf(filter) > -1) { content[i].style.display = ""; } else { content[i].style.display = "none"; } } } } 
 <div class="search-bar"> <input type="text" id="search" onkeyup="search()"placeholder="Search for numbers"> </div> <div id="search-list"> <span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> </div> 

  • content is an nodelist and you need to access index to access node content是一个节点列表,您需要访问索引才能访问节点
  • you defined variable as txtValue in console you're using textValue 你定义变量txtValue在控制台你使用textValue

 function search() { var input, filter, e, content, txtValue; input = document.getElementById("search"); filter = input.value.toUpperCase(); e = document.getElementById("search-list"); content = e.getElementsByTagName("span"); for (i = 0; i < content.length; i++) { if (content) { txtValue = content[i].innerHTML; if (txtValue.toUpperCase().indexOf(filter) > -1) { content[i].style.display = ""; } else { content[i].style.display = "none"; } } } } 
 <div class="search-bar"> <input type="text" id="search" onkeyup="search()"placeholder="Search for numbers"> </div> <div id="search-list"> <span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> </div> 

Maybe you need to use: 也许您需要使用:

txtValue = content[i].innerHTML; txtValue = content [i] .innerHTML;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM