0

I have written the following code that aims to create a div and within it a nested span. Here is the code. Its results buffle me:

function(){
    $("<div>", {
    text: "<span>SomeText</span>",
    class: "queryTitle"
}).prependTo(container);

When inspected in chrome this is the resulting html:

<div class="queryTitle"><span>1234</span></div>

And while this is the exact html I am aiming for, this html is not rendered properly in the browser, as the span block displays "unrendered" in the browser, like below:

<span>1234</span>

(I understand I can rewrite the code like below

function(){
  $("<div class = " + queryTitle + "><span>1234</span></div>").prependTo(container)
}

which returns the desired result, yet I find this syntax a bit unreadable, plus I would really like to understand what I am doing wrong as an educational drill.

Thank you for reading.

4

1 回答 1

10

text函数将创建一个 textNode,它不会将其内容视为 html(以明文形式显示 span 标签)。改用html

function(){
    $("<div>", {
    html: "<span>SomeText</span>",
    'class': "queryTitle"
}).prependTo(container);

编辑-为清楚起见,您的代码等效于:

$("<div>")
    .text("<span>SomeText</span>") // creates a textNode and appends it
    .addClass("queryTitle")
    .prependTo(container);

你真正想要的地方:

$("<div>")
    .html("<span>SomeText</span>") // sets innerHTML
    .addClass("queryTitle")
    .prependTo(container);

可以在此处找到(有点)描述第一种语法的文档:http: //api.jquery.com/jQuery/#jQuery2

注意:将 HTML 字符串放入 JavaScript 通常是个坏主意。您不应该这样做,因为随着项目的发展,它变得难以维护。

于 2013-01-11T17:39:54.597 回答