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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9497820/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:52:44  来源:igfitidea点击:

Store HTML code in a string in javascript

javascripthtml

提问by user1196522

I am copying the "view source" of an external html page (1.html) into a variable in javascript in another html page (2.html). But due to the indentation, quotes, spaces and tags in the html page, i am not able to store all of the source code in the string at one go. Is there any function which can be used to do so?

我正在将外部 html 页面 (1.​​html) 的“查看源代码”复制到另一个 html 页面 (2.html) 中的 javascript 变量中。但是由于 html 页面中的缩进、引号、空格和标签,我无法一次性将所有源代码存储在字符串中。有什么功能可以用来这样做吗?

Contents of 1.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>

Contents of 2.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>

if a paste all the contents copied from 1.html after var=" inside 2.html, it does not take all of it.. Any solution to this?

如果将所有从 1.html 复制的内容粘贴到 2.html 中的 var=" 之后,它不会全部删除.. 有什么解决方案吗?

回答by package

You cannot store multiline text in javascript string. To store that html in javascript you have to escape quotes and remove whitespace. Some examples:

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

This won't work:

这行不通

var str = "Multiline
Text";

This won't work either:

这也行不通

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

This will work:

这将工作

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

回答by soju

You forgot to escape quote :

你忘了转义引用:

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

And replace new line with \n

并将新行替换为\n