答:使用串联运算符 (+)
使用串联运算符(+)在JavaScript变量中分配或存储HTML代码块的最简单,最安全的方法。在对HTML代码块进行说明时,应使用单引号,这样会更容易在实际HTML代码中保留双引号。
您还需要转义出现在HTML块内容内的单引号-只需将'字符替换为\',如以下示例所示:
例试试这个代码»
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Store HTML Code in JavaScript Variable</title>
</head>
<body>
<div id="wrapper"></div>
<script>
// Storing HTML code block in a variable
var codeBlock = '<div class="content">' +
'<h1>This is a heading</h1>' +
'<p>This is a paragraph of text.</p>' +
'<p><strong>Note:</strong> If you don\'t escape "quotes" properly, it will not work.</p>' +
'</div>';
// Inserting the code block to wrapper element
document.getElementById("wrapper").innerHTML = codeBlock
</script>
</body>
</html>
如果您觉得本文的内容对您的学习有所帮助:
关键字:
jQuery