javascript - JQuery .text() 用于数组中的元素

标签 javascript jquery html arrays

我想首先找到 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/

相关文章:

javascript - 元素在页面上显示为 <span class ="icon"></span> 而不是被渲染

javascript - FireFox 是否缓存 jquery.ajax 返回?

javascript - Jquery Header 在悬停时添加类

javascript - jQuery + 正则表达式替换文本区域内的 href 和 src 值

css - 下拉菜单中的第三层仅在 IE7 中不起作用

javascript - 尝试从点击事件coffeescript中调用 'this'

javascript - 谷歌图表 : Switching between Line and Column charts

javascript - 为什么需要设置原型(prototype)构造函数?

javascript - 如何缓存光栅化图像

javascript - ajax不是通过jquery调用的