Jquery 找不到链接

Jquery not finding links

我有以下代码 Jquery。

var myHTML = $(`<a href="/wiki/Indian_Rebellion_of_1857" title="Indian Rebellion of 1857">Indian Rebellion of 1857</a>: Indian rebels seize Delhi from the British.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11">[11]</a></sup>`)
var firstLinkText = myHTML.find("a:first").text()

console.log(firstLinkText)

// Output "[11]"

我不知道为什么第一个 link <a> 没有被选中,而是最后一个?我的代码有什么问题,有什么修复方法吗?

var html = `<a href="/wiki/Indian_Rebellion_of_1857" title="Indian Rebellion of 1857">Indian Rebellion of 1857</a>: Indian rebels seize Delhi from the British.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11">[11]</a></sup>`
var myHTML = $(html)

var firstLinkText = myHTML.find("a:first").text()
console.log(firstLinkText)
document.body.textContent = (html)
document.write("<br><br>Output: " + firstLinkText)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

问题是因为通过使用 find() 你告诉 jQuery 寻找你在 父元素中 提供的选择器。由于父级本身是 a 元素,因此它显然找不到任何东西。

要解决此问题,您可以改用 filter():

var $myHTML = $(`<a href="/wiki/Indian_Rebellion_of_1857" title="Indian Rebellion of 1857">Indian Rebellion of 1857</a>: Indian rebels seize Delhi from the British.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11">[11]</a></sup>`)
var firstLinkText = $myHTML.filter('a:first').text()

console.log(firstLinkText)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

.find() 仅搜索后代中的匹配项,而不是集合中的 top-level 元素。所以你需要将 HTML 包裹在 <div> 中,这样一切都是后代。

var myHTML = $(`<div><a href="/wiki/Indian_Rebellion_of_1857" title="Indian Rebellion of 1857">Indian Rebellion of 1857</a>: Indian rebels seize Delhi from the British.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11">[11]</a></sup>`)
var firstLinkText = myHTML.find("a:first").text()

console.log(firstLinkText)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

看来 html 字符串必须是带有子元素的单个元素。

似乎无法使用 :first,方法是在没有父项的情况下放置带有两个 HTML 标签的字符串。

您的问题的解决方案可以是将您的 html 包裹在任何标签中以便搜索您的元素。

const html = `<a href="/wiki/Indian_Rebellion_of_1857" title="Indian Rebellion of 1857">Indian Rebellion of 1857</a>: Indian rebels seize Delhi from the British.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11">[11]</a></sup>`

var myHTML = $(`<span>${html}</span>`)
var firstLinkText = myHTML.find("a:first").text()

console.log(firstLinkText)

// Output "Indian Rebellion of 1857"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

另一个答案中的 .filter() 方法非常有趣且速度更快! 我留下我的答案作为替代...