我想首先找到 html 文档中具有相同类名并且是 anchor 标记的所有元素,并从中获取文本。
HTML:
<div class="links" id="one">
<span class="info">useless links</span>
<a class="anchorTag" href="www.sample.com">Click me!</a>
<a class="anchorTag" href="www.sample.com">Click me again!</a>
<a class="anchorTag" href="www.sample.com">Click me once again!</a>
<a class="anchorTag" href="www.sample.com">Click me one last time!</a>
</div>
<div class="links" id="two">
<span class="info">secret links</span>
<a class="anchorTag" href="www.sample.com">Click me!</a>
<a class="anchorTag" href="www.sample.com">Click me again!</a>
<a class="anchorTag" href="www.sample.com">Click me once again!</a>
<a class="anchorTag" href="www.sample.com">Click me one last time!</a>
</div>
代码:
$('.links').each(function(){
if($(this).find("span.info").text() == "secret link"){
var allLinks = $(this).find("a.anchorTag");
console.log(allLinks[0].text());
}
});
错误:
console.log(allLinks[0].text()) is not a function
如果我打印 var allLinks 的长度,它会返回正确的大小,但在使用索引访问数组时不会打印数组中特定元素的文本?为什么会这样?
最佳答案
allLinks 不是一个实际的数组,而是一组 DOM 元素。也就是说,普通的数组运算符无法处理它。如果您想打印集合中第一个元素的文本,而不是这样:
console.log(allLinks[0].text());
您应该像这样使用 jquery .first() 方法:
console.log(allLinks.first().text());
关于javascript - JQuery .text() 用于数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38599294/