将HTML代码存储在javascript中的字符串中

Store HTML code in a string in javascript

本文关键字:字符串 javascript HTML 代码 存储      更新时间:2023-09-26

我正在将外部html页面(1.html)的"视图源代码"复制到另一个html页面(2.html)的javascript变量中。但由于html页面中的缩进、引号、空格和标记,我无法一次性将所有源代码存储在字符串中。有什么函数可以用来做这件事吗?

1.html:的内容

<html>
<head>
    <title>1 </title>
</head>
<body>
    This is just plain text body
    <div id="new"> This id div text</div>
    <span> This is span text </span>
</body>
</html>

2.html:的内容

<html>
<head>
<script type="text/javascript" language="javascript">
var str="<html>
<head>
    <title>2 </title>
</head>
<body>
    This is just plain text body
    <div id="new"> This id div text</div>
    <span> This is span text </span>
</body>
</html>";
alert (str);
</script>
</head>
<body>
</body>
</html>

如果将从1.html复制的所有内容粘贴在var="inner 2.html之后,它不会占用所有内容。有什么解决方案吗?

不能将多行文本存储在javascript字符串中。要将该html存储在javascript中,您必须转义引号并删除空白。一些例子:

这不起作用

var str = "Multiline
Text";

这也不起作用

var str = "Non-escaped text with "double quotes" and 'single quotes'";

这将起作用

var str = "This will work because the '"double quotes'" are escaped";

您忘记转义引号:

    <div id='"new'"> This id div text</div>

并用'n 替换新行