使用 javascript/jquery 用 html 填充 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16019621/
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
Fill div with html using javascript/jquery
提问by valenz
here is my problem:
这是我的问题:
I have a div:
我有一个 div:
<div id="legend"></div>
and I want to fill it, under certain conditions, with this other code:
我想在某些条件下用其他代码填充它:
<p>Showing results....
Key:
<img src="/...."><=1
<img src="/..."><=2
<img src="/..."><=3
<img src="/..."><=4
<img src="/..."><=5
<p>
As you can see this is a legend and the main issue I think is that I have double quotes that cannot be easily included using for instance the solution here: Fill div with text
正如您所看到的,这是一个图例,我认为的主要问题是我有双引号不能很容易地使用,例如使用这里的解决方案: Fill div with text
Thanks for your help!
谢谢你的帮助!
回答by Niet the Dark Absol
By my understanding, you are trying to do something like this:
据我了解,您正在尝试执行以下操作:
$("#legend").text("Your HTML here");
To insert HTML, you should use .html()
, HOWEVER it would be far more efficient to just use Vanilla JSlike so:
要插入 HTML,您应该使用.html()
,但是像这样使用Vanilla JS会更有效率:
document.getElementById('legend').innerHTML = "Your HTML here";
Now, you also mention having problems with double-quotes. Well, there are two possible solutions.
现在,您还提到了双引号问题。那么,有两种可能的解决方案。
1: Use single-quotes around your string: '<img src="/..." />'
2: Escape the quotes: "<img src=\"/...\" />"
1:在字符串周围使用单引号:'<img src="/..." />'
2:转义引号:"<img src=\"/...\" />"
And one more thing: If those newlines are actually in your HTML to insert, you can't have a multi-line string in JavaScript. You have two options here too:
还有一件事:如果这些换行符实际上在要插入的 HTML 中,则 JavaScript 中不能有多行字符串。您在这里也有两个选择:
1: Escape the newline:
1:转义换行符:
"<p>\
Hello, world!\
</p>"
2: Concatenate:
2:连接:
"<p>\n"
+"Hello, world!\n"
+"</p>"
回答by Adriano Carneiro
Assemble your html code in a variable according to your conditions (which we do not know), then use html()
to set it to the element.
根据您的条件(我们不知道)将您的 html 代码组装到一个变量中,然后使用html()
将其设置为元素。
var yourHtml = "your html";
$("#legend").html("yourHtml");
As for dealing with the quotes, you can either use single quotes in variable, such as:
至于处理引号,你可以在变量中使用单引号,例如:
var yourHtml = '<img src="/yourimgr.png">';
or you can escape the double quotes:
或者你可以转义双引号:
var yourHtml = "<img src=\"/yourimgr.png\">";
回答by PranitG
- Store your paragraph html in some string
var str= <p>write your complete code here</p>
$('#legend').html(yourconditionSatisfies?str:'')
- 将您的段落 html 存储在某个字符串中
var str= <p>write your complete code here</p>
$('#legend').html(yourconditionSatisfies?str:'')