Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery等价于insertNode?_Javascript_Jquery - Fatal编程技术网

Javascript jQuery等价于insertNode?

Javascript jQuery等价于insertNode?,javascript,jquery,Javascript,Jquery,我正在致力于将纯JS文本突出显示脚本转换为jQuery,但我正在试图弄清楚jQuery与insertNode的等价关系: var selection = window.getSelection().getRangeAt(0); var selectedText = selection.extractContents(); var span = document.createElement("span"); span.style.backgroundColor = "yellow"; span.a

我正在致力于将纯JS文本突出显示脚本转换为jQuery,但我正在试图弄清楚jQuery与
insertNode
的等价关系:

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);
使用prepend()或append()或insertAfter()或insertAt()


$(选择).append()

我认为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
var selection=window.getSelection().getRangeAt(0);
var selectedText=selection.extractContents();
变量span=$(“”+selectedText.textContent+“”);
selection.insertNode(span[0]);//传递jQuery对象中的第一个节点

要插入元素,而不是jQuery对象:

selection.insertNode(span[0]);

使用
selection.append(span)
会导致
TypeError:“未定义”不是函数(评估“selection.append(span)”)
@Charlie:您只能在jQuery对象上使用jQuery方法。您的编辑会导致
TypeError:“未定义”不是插入
的函数(评估“context.createDocumentFragment()”)
[object DocumentFragment]
…嗯,关于span[0]。第一个孩子?我一定错过了这个:原始插入的
[object DocumentFragment]
,而注释插入的只是
[object DocumentFragment]
等等,DocumentFragment实际上是您的
selectedText
,而不是span[0]我建议selectedText.textContent,看看我刚才添加到答案中的代码。你可以在这个页面上测试它,选择一些东西并将代码粘贴到控制台。如果JavaScript有效,为什么要转换它?我页面的其余部分在jQuery中,所以我希望它是统一的。jQuery是JavaScript。我从来没有声称它不是。是的,我可以理解以及对一致性的渴望。使用jQuery链插入“常规”javascript时不必中断,这样更好。
selection.insertNode(span[0]);