我有以下 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" ><a href="#cite_note-11">[11]</a></sup>`)
var firstLinkText = myHTML.find("a:first").text()
console.log(firstLinkText)
// Output "[11]"
我不知道為什么第一個鏈接<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" ><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>
uj5u.com熱心網友回復:
問題是因為使用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" ><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>
uj5u.com熱心網友回復:
.find()僅搜索后代中的匹配項,而不是集合中的頂級元素。因此,您需要將 HTML 包裝在 a 中<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" ><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>
uj5u.com熱心網友回復:
似乎 html 字串必須是帶有子元素的單個元素。
似乎不可能通過放置一個帶有兩個沒有父標簽的 HTML 標簽的字串來使用 :first 。
您的問題的解決方案可以是將您的 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" ><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() 方法非常有趣且速度更快!我留下我的答案作為替代...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/472742.html
標籤:javascript jQuery
