我正在嘗試從作為字串拉入的 HTML 中提取影像屬性。
嘗試使用https://stackoverflow.com/a/40311944/2981404回傳:
TypeError: Cannot read properties of undefined (reading 'slice')
我的代碼如下:
const html[0] = '<img src="/img/image-example.png" title="What Im looking for..." alt="從 HTML 字串獲取屬性(沒有 jQuery)">'
const startFromTitle = html[0].slice(
html[0].search('title')
)
const title = startFromTitle.slice(5, startFromTitle.search(' ') - 1)
console.log(title) // expected "What Im looking for..."
我很想使用 jQuery,但在這個專案中,我不能。
uj5u.com熱心網友回復:
div您可以通過在 DOM 中創建一個臨時元素來實作此目的:
const htmlStr = '<img src="/img/image-example.png" title="What Im looking for..." alt="從 HTML 字串獲取屬性(沒有 jQuery)">';
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = htmlStr;
console.log(tmpDiv.querySelector('.image').getAttribute('title'));
uj5u.com熱心網友回復:
您必須先宣告html為const,然后將 html 字串分配給 html[0]。
然后您可以title="從字串中洗掉 ( withoutTitle) ,然后搜索'"'以找到屬性的結尾。
const html = [];
html[0] = '<img src="/img/image-example.png" title="What Im looking for..." alt="從 HTML 字串獲取屬性(沒有 jQuery)">';
const startFromTitle = html[0].slice(
html[0].search('title')
);
const withoutTitle = startFromTitle.slice(
7
);
const title = withoutTitle.slice(0, withoutTitle.search('"'));
console.log(title);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/443806.html
標籤:javascript 细绳 片
