如何使用document.createElement()創建可關閉的警報?
我正在嘗試添加以下警報:
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
使用document.createElement()如下代碼所示的函式:
document.createElement('
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>'
);
但不斷收到以下錯誤訊息:Uncaught SyntaxError: Invalid or unexpected token。
瀏覽器控制臺提示錯誤在這一行 <div role="alert">
我究竟做錯了什么?
uj5u.com熱心網友回復:
你不能像那樣使用 createElement 。
句法
創建元素(標簽名)
創建元素(標簽名,選項)
標簽名
一個字串,它指定要創建的元素的型別。所創建元素的 nodeName 用 tagName 的值初始化。不要在此方法中使用限定名稱(如“html:a”)。在 HTML 檔案上呼叫時,createElement() 在創建元素之前將 tagName 轉換為小寫。在 Firefox、Opera 和 Chrome 中,createElement(null) 的作業方式類似于 createElement("null")。
請參考 mdn 檔案。
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
在這種情況下,您可以使用 DOMParser 將字串決議為 HTMLElement。
例如
const parser = new DOMParser()
const dom = parser.parseFromString(`
<div role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>`, 'text/html')
console.log(dom.body.firstChild)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507473.html
標籤:javascript html 推特引导 警报
