将整个元素插入另一个元素,而不仅仅是其内部 HTML
我试图弄清楚如何使用 jQuery 尽可能合理地构建 HTML。据我所知,这应该产生
,但会产生
:
post = $("<div>");
username = $("<span>").html("Alice");
post.append(username);
我发现用 post.append(username.html())
替换最后一行可以让我更接近我的目标,但它如果我这样做的话,就会省略 标签。如何插入带有周围标签的子元素,而不写出
"" + username + ""
,这似乎是完成该任务的新手方法?
编辑:愚蠢的错误。我上面发布的代码片段过于简化;我真的很想在我的代码中执行 post.append(username + another_span_element)
。显然我不能像这样附加对象。我已将其更改为 post.append(username); post.append(another_span_element); 现在它工作正常。杜尔!
I'm trying to figure out how to use jQuery to construct HTML as sanely as possible. As far as I can tell, this should produce <div><span>Alice</span></div>
, but instead produces <div>[object Object]</div>
:
post = $("<div>");
username = $("<span>").html("Alice");
post.append(username);
I've found that replacing the last line with post.append(username.html())
gets me closer to my goal, but it omits the <span>
tags if I do it that way. How do I insert a child element with the surrounding tags, and without writing out "<span>" + username + "</span>"
, which seems like a novice approach to the task?
EDIT: Stupid mistake. The snippet I posted above was excessively simplified; I was really trying to do post.append(username + another_span_element)
in my code. Obviously I can't append objects like that. I've changed it to post.append(username); post.append(another_span_element);
and now it works fine. Durr!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对我有用:
$("
").append($("").html("Alice"))[0].outerHTML == "< span>爱丽丝
"
Works for me:
$("<div>").append($("<span>").html("Alice"))[0].outerHTML == "<div><span>Alice</span></div>"
您的目标是通过 text() 方法完成:
此处示例。
What you're aiming for is done with the text() method:
Example here.
是否有理由不执行:
或
或
或
或其他 200 个选项中的任何一个?
Is there a reason for not doing:
or
or
or
or any of the other 200 options?