我正致力于将纯 JS 文本突出显示脚本转换为 jQuery,但我试图找出与 insertNode
等效的 jQuery 是什么:
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.appendChild(selectedText);
selection.insertNode(span);
我想我可以使用以下内容:
var span = $("<span class='highlight'>" + selectedText + "</span>");
selection.insertNode(span);
结果是:
NOT_FOUND_ERR: DOM Exception 8: An attempt was made to reference a Node in a context where it does not exist.
最佳答案
我不认为 jQuery 可以对选择进行操作,您必须使用常规的 JS 方法。你得到一个错误,因为你的 span
是一个 jQuery 对象,而不是一个节点。
此外,selection.extractContents()
将返回一个 DocumentFragment,而不是一个字符串。所以试试这个:
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = $("<span class='highlight'>" + selectedText.textContent + "</span>");
selection.insertNode(span[0]); // pass the first node in the jQuery object
关于javascript - jQuery 等同于 insertNode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15234440/