javascript Jquery:将 HTML 附加到包含 HTML 的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16707258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery: Append HTML to a variable containing HTML
提问by MeltingDog
I have a var containing a bunch of HTML. I want to append a link to it before appending the var to a wrapper div,eg:
我有一个包含一堆 HTML 的 var。我想在将 var 附加到包装器 div 之前附加一个链接,例如:
var content = '~html generated from JSON~'
$content.append.("<a href='link'>Link</a>");
I've tried a few ways of doing this but I cant get it right or find any info on SO.
我已经尝试了几种方法来做到这一点,但我无法做到正确或找不到任何关于 SO 的信息。
Do I need to 'explode' the variable before hand?
我需要事先“爆炸”变量吗?
Does anyone know how to achieve this?
有谁知道如何实现这一目标?
回答by John Postlethwait
You can select your generated HTML with the jQuery selector, which will parse it into actual DOM nodes. From there you can do whatever you need to with it:
您可以使用 jQuery 选择器选择生成的 HTML,它将把它解析为实际的 DOM 节点。从那里你可以做任何你需要的事情:
var $content = $('~html generated from JSON~'),
$link = $('<a href="link">Link</a>');
$content.find('span').append($link);
回答by Michiel
just do
做就是了
content += "<a href='link'>Link</a>";
$contentis not the same as content, acutally $contentis something you would have to declare yourself, usually when you use jQuery the $ prefix is used for variables that relate to something on the dom to which you can apply jQuery methods. So if $contentwas a domnode you can do $content.append, but not before you declare it. Your contentvariable is a string to which jQuery methods do not apply.
$content与content 不同,实际上$content是您必须自己声明的东西,通常当您使用 jQuery 时, $ 前缀用于与 dom 上的某些内容相关的变量,您可以在其中应用 jQuery 方法。因此,如果$content是一个 domnode,您可以执行 $content.append,但不能在声明它之前执行。您的内容变量是一个字符串,jQuery 方法不适用于该字符串。