获取jQuery链接的文本

时间:2016-02-24 05:12:47

标签: jquery google-chrome-extension undefined href

所以我正在尝试开发自己的Chrome扩展程序。首次尝试,我想创建一个扩展,将页面中的所有链接收集到一个地方。
由于我不知道有哪种链接,我必须通过选择其属性来获取链接href和链接文本。
链接$("a[href^='http']").eq(i).innerHTML属性选择器工作正常,但我似乎无法使用我的代码获取链接文本。它总是返回undefined。这是我的代码:
$("a[href^='http']").eq(i)
(我是for循环中的变量,只是假装它是一些数字)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <body><a href="https://www.google.com/">link1</a><a href="https://www.google.com/">link2</a><a href="https://www.google.com/">link3</a> </body> <p id="log">Pretend this is the console: </p> <script> for (var i = 0; i < document.links.length; i++) { document.getElementById("log").innerHTML += ($("a[href^='http']").eq(i).attr("href") + " (" + $("a[href^='http']").eq(i).innerHTML + ") / "); } </script> </html>应该返回元素,对吧?那我错过了什么?

这里有一个片段向您展示我的意思:

&#13;
&#13;
play
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

innerHTML是一个方法,而不是属性,使用它如下:$("a[href^='http']").eq(i).innerHTML()

为了澄清,.eq(i)方法不返回DOMElement,而是jQuery对象。 jQuery对象具有innerHTML()方法 - 它返回jQuery对象引用的元素内的html字符串。

在旁注 - 看到你正在寻找文本,而不是html,也许你真的会更好地使用.text()方法?

答案 1 :(得分:0)

我假设下面的链接由选择器

重新调整
-i

如果要检索链接文本,请尝试

<a href="http://chat.stackoverflow.com" class="js-gps-track" data-gps-track="site_switcher.click({ item_type:6 })">chat</a>

如果您想要检索链接网址,请尝试

$("a[href^='http']").eq(i).text() 

答案 2 :(得分:0)

获取所有标记并对其进行迭代,您可以获得 href值作为以下代码:

$("body").find('a').each(function() {
    console.log($(this).attr('href'));
});

检查一下, https://jsfiddle.net/mogaax3g/

答案 3 :(得分:0)

您可以按照以下方式获取上述代码。正如在注释中提到的那样,JQuery返回的是一个JQuery对象。要访问实际元素,请在JQuery对象之后使用索引。

$("a[href^='http']")[i].innerHTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body><a href="https://www.google.com/">link1</a><a href="https://www.google.com/">link2</a><a href="https://www.google.com/">link3</a>
</body>
<p id="log">Pretend this is the console: </p>
<script>
  for (var i = 0; i < document.links.length; i++) {
    document.getElementById("log").innerHTML += ($("a[href^='http']").eq(i).attr("href") + " (" + $("a[href^='http']")[i].innerHTML + ") / ");
  }
</script>

</html>

相关问题