[英]How can I add a <use> to an inline SVG using jQuery (or plain JavaScript if needed)?
[英]Can I use JavaScript fetch() to insert an inline svg in the DOM?
我有一個使用 XMLHttpRequest() 在 DOM 中插入內聯 svg 的函數,我想知道是否可以使用 fetch() 執行相同的功能。 功能是...
el = document.querySelector('#foo')
var request = new XMLHttpRequest()
request.open('GET', 'bar.svg', true)
request.onreadystatechange = function() {
if (this.readyState !== 4) return
if (this.status !== 200) return
el.innerHTML = this.responseText
}
request.send()
// bar.svg is inserted in element with ID 'foo'
那么,是否可以將此功能現代化為類似...
fetch('bar.svg').then(...)
你可以。 我認為以下應該有效:
fetch('bar.svg')
.then(r => r.text())
.then(text => {
el.innerHTML = text;
})
.catch(console.error.bind(console));
第二then
是解決.text()
其中“需要一個響應流,並將其讀入到完成”( MDN )。
是的,fetch 返回一個 promise。所以你可以使用 then() 和 catch(error) 來捕獲錯誤。 但要注意瀏覽器兼容性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.