我正在创建一个 JavaScript 框架来构建 HTML 文档。首先使用 jQuery 构建一个虚拟文档。现在,我正在试验 jQuery 的“add”函数,如下所示:
$(target).append($("").add($("<div>")).add($("<span>")))
The framework concatenates these calls to build the virtual document before it is appended to the target - this simplified code sample isn't literally what I'm doing. The reason for adding the first $("") is because the framework starts by creating an empty jQuery selection then adds stuff to it. Sub-documents are recursively created and added to parent elements.
这对于将元素连接在一起效果很好,但是如果我想连接文本怎么办?假设我想要呈现这样的内容:
<div></div> Outside the box!
我不能只做$("<div>").add("Outside the box!")
另外,$.after()
似乎不起作用,除非 <div>
已经在 DOM 上。
jQuery 支持此功能吗?如果没有,有什么解决方法吗?
最佳答案
是的,您可以使用简单的字符串连接与元素的当前 HTML:$('<div>').html($('<div>').html() + 'Outside the box!')
由于您的代码 DOM 在内存中而不是实际的 HTML,因此您需要使用多行代码:
var $div = $('<div>', {html: $('<div>')});
$div.html($div.html() + "Outside the box!");
关于javascript - 有没有办法将非元素包含的文本添加到 $ ("")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41137867/