[英]How to set an “id” to a tag using the execCommand in Javascript?
我正在嘗試編寫一個基本的文本編輯器,為此我經常使用 execCommand。 但是,我想以這種方式創建標題,以便每當用戶單擊標題按鈕(在文本編輯器中)時, execCommand 將組成一個新標題並應將id添加到新創建的標題,以便,稍后我只需單擊一下即可在文檔中創建互連。
假設我在標題文本編輯器中的輸入是:
創建一個帶有 id 的標題
我試過這個來創建一個帶有 id 的標題:
document.execCommand('formatBlock', false, header).id = userSelection;
用於此的 HTML 輸出:
<h3><a href="#Create a heading with id">Create a heading with id</a></h3>
如您所見,該 id 未添加到 HTML 輸出中,那么如何向其添加 id?
我也試過這個鏈接,但沒有得到太多:
如何在 execCommand formatBlock 'p' 標簽中添加類或 id 或 CSS 樣式?
請幫忙:)
編輯:
好吧,我有一個技巧可以做到這一點:
我們可以使用查詢選擇器將 id 添加到新創建的標簽中,這樣每當我使用 execCommand 創建新標簽時,我都會通過選擇主 div(正在編輯的地方)找到該標簽,然后找到標頭標簽,我可以簡單地將 id 添加到它。
就像我用它在 div(contenteditable="true") 中創建標題標簽一樣:
document.execCommand('formatBlock', false, header);
要將“id”添加到這個新創建的標簽,請使用以下命令:
let elemMain = $("#editor " + header);
// this will find the div with id="editor" and then find the header tag inside it.
elemMain[elemMain.length - 1].id = userSelection;
//this will add an id to the last header tag inside of div.
好吧,這只是完成工作的一種技巧,但是如果有人找到了使用 execCommand 將“id”添加到標記的直接方法,那么非常歡迎:)
在這里使用 execCommand 將 id 屬性添加到<body>
標記。
使用 javascript :
var idValue = "body-element";
document.execCommand(document.body.setAttribute("id", idValue));
使用 jquery :
var idValue = "body-element";
document.execCommand($('body').attr('id', idValue));
新創建元素的工作片段:
var para = document.createElement("p"); var node = document.createTextNode("This is newly created paragraph ( inspect this element and see the id.)"); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); var idValue = "new_id"; document.execCommand(para.setAttribute("id", idValue));
<html> <body> <div id="div1"> <p id="p1">This is an old paragraph.</p> </div> </body> </html>
有相同的要求使用document.execCommand
來操作contenteditable
元素,並最終求助於execCommand
的innerHTML
選項。 例如...
document.execCommand("insertHTML", false, "<div id='myId'>Hello World!</div>")
...在插入點添加指定的 HTML,留下可由myId
尋址的 HTML 元素。 這種技術的缺點是必須構造 HTML 字符串。 另一種方法是采用createElement
函數,然后引用該outerHTML
呼叫時該元素節點execCommand
...
let elemNode = document.createElement('div')
elemNode.id = 'myId'
elemNode.innerText = 'Hello World!'
document.execCommand('insertHTML', false, elemNode.outerHTML)
請注意,我僅在 Chrome 上對此進行了測試。
希望這可以幫助其他人找到互聯網的這個角落。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.