[英]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.