[英]js: can I assign a class or an id to an html-element that's part of a variable definition?
NOTE: My knowledge of programming is scant. 注意:我的编程知识很少。
I've got this line of code somewhere: 我在某处有以下代码行:
var item = "<h3>" + '<a href="' + postUrl + '" target="_blank">' + postTitle + "</a> </h3> <p>" + postContent + "</p>";
postUrl
, postTitle
and PostContent
have previously been declared. postUrl
, postTitle
和PostContent
先前已声明。
I'd like to wrap it all up inside a <div>
tag that has some class or id assigned to it, as in... 我想将其全部包装在
<div>
标记中,该标记已为其分配了某些类或ID,如...
var item = "<div id="special"> <h3>" + '<a href="' + postUrl + '" target="_blank">' + postTitle + "</a> </h3> <p>" + postContent + "</p> </div>";
But that doesn't seem to work. 但这似乎不起作用。
Is it because of the quotations getting messed up or is it the wrong way to go altogether? 是因为报价混乱了还是完全走错了路?
You have two options: 您有两种选择:
"
quotes inside your string literal, like this: "<div id=\\"special\\"> <h3>"
"
你的字符串引号内的文字,就像这样: "<div id=\\"special\\"> <h3>"
'
for either the outer string or inner one (you have the choice) , like this: '<div id="special"> <h3>'
or "<div id='special'> <h3>"
'
作为外部字符串或内部字符串(您可以选择) ,例如: '<div id="special"> <h3>'
或"<div id='special'> <h3>"
I personally prefer '<div id="special"> <h3>'
because the generated HTML
will contain the "
quotes (which is the HTML standard) while keeping the JavaScript
more readable and maintainable (compared to using escaped quotes) 我个人更喜欢
'<div id="special"> <h3>'
,因为所生成的HTML
将包含"
引号(它是HTML标准),同时保持JavaScript
可读性和可维护性(相比于使用转义引号)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.