如何在 JavaScript 中插入一大块 HTML?

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

How to insert a large block of HTML in JavaScript?

javascripthtml

提问by Hello

If I have a block of HTML with many tags, how do insert it in JavaScript?

如果我有一个带有许多标签的 HTML 块,如何将它插入到 JavaScript 中?

var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = 'HERE TOO MUCH HTML that is much more than one line of code';
document.getElementById('posts').appendChild(div);

How do I do it right?

我该怎么做才正确?

回答by Danny Beckett

You could keep the HTML block in an invisible container (like a <script>) within your HTML code, then use its innerHTMLat runtime in JS

您可以将 HTML 块保存在 HTML 代码中的不可见容器(如<script>)中,然后innerHTML在运行时在 JS 中使用它

For example:

例如:

var div = document.createElement('div');
div.setAttribute('class', 'someClass');
div.innerHTML = document.getElementById('blockOfStuff').innerHTML;
document.getElementById('targetElement').appendChild(div);
.red {
    color: red
}
<script id="blockOfStuff" type="text/html">
    Here's some random text.
    <h1>Including HTML markup</h1>
    And quotes too, or as one man said, "These are quotes, but
    'these' are quotes too."
</script>

<div id="targetElement" class="red"></div>

Idea from this answer: JavaScript HERE-doc or other large-quoting mechanism?

来自这个答案的想法:JavaScript HERE-doc or other large-quoting mechanism?



Related:

有关的:

If you want to insert a particularly long block of HTML in PHP you can use the Nowdoc syntax, like so:

如果要在 PHP 中插入特别长的 HTML 块,可以使用 Nowdoc 语法,如下所示:

<?php

    $some_var = " - <b>isn't that awesome!</b>";

    echo
<<<EOT
    Here's some random text.
    <h1>Including HTML markup</h1>
    And quotes too, or as one man said, "These are quotes, but 'these' are quotes too."
    <br><br>
    The beauty of Nowdoc in PHP is that you can use variables too $some_var
    <br><br>
    Or even a value contained within an array - be it an array from a variable you've set
    yourself, or one of PHP's built-in arrays. E.g. a user's IP: {$_SERVER['REMOTE_ADDR']}
EOT;

?>

Here's a PHP Fiddle demoof the above code that you can run in your browser.

这是您可以在浏览器中运行的上述代码的 PHP Fiddle 演示

One important thing to note:The <<<EOTand EOT;MUSTbe on their own line, without any preceding whitespace.

需要注意的一件重要的事情:<<<EOTEOT;必须对自己行,没有任何前面的空白。



One huge advantage of using Nowdoc syntax over the usual starting and stopping your PHP tag is its support for variables. Consider the usual way of doing it (shown in the example below), contrasted to the simplicity of Nowdoc (shown in the example above).

与通常开始和停止 PHP 标记相比,使用 Nowdoc 语法的一大优势是它对变量的支持。考虑通常的执行方式(如下例所示),与 Nowdoc 的简单性(如上例所示)形成对比。

<?php

    // Load of PHP code here

?>

Now here's some HTML...<br><br>

Let's pretend that this HTML block is actually a couple of hundred lines long, and we
need to insert loads of variables<br><br>

Hi <?php echo $first_name; ?>!<br><br>

I can see it's your birthday on <?php echo $birthday; ?>, what are you hoping to get?

<?php

    // Another big block of PHP here

?>

And some more HTML!
</body>
</html>

回答by Vadakkumpadath

Template literalsmay solve your issue as it will allow writing multi-line strings and string interpolation features. You can use variables or expression inside string (as given below). It's easy to insert bulk html in a reader friendly way.

Template literals可能会解决您的问题,因为它将允许编写多行字符串和字符串插值功能。您可以在字符串中使用变量或表达式(如下所示)。以读者友好的方式插入批量 html 很容易。

I have modified the example given in question and please see it below. I am not sure how much browser compatible Template literalsare. Please read about Template literalshere.

我已经修改了有问题的示例,请在下面查看。我不确定浏览器的兼容性Template literals有多少。请在此处阅读有关模板文字的信息。

var a = 1, b = 2;
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = `
    <div class="parent">
        <div class="child">${a}</div>
        <div class="child">+</div>
        <div class="child">${b}</div>
        <div class="child">=</div>
        <div class="child">${a + b}</div>
    </div>
`;
document.getElementById('posts').appendChild(div);
.parent {
  background-color: blue;
  display: flex;
  justify-content: center;
}
.post div {
  color: white;
  font-size: 2.5em;
  padding: 20px;
}
<div id="posts"></div>

回答by Geuis

Despite the imprecise nature of the question, here's my interpretive answer.

尽管问题的性质不精确,但这是我的解释性答案。

var html = [
    '<div> A line</div>',
    '<div> Add more lines</div>',
    '<div> To the array as you need.</div>'
].join('');

var div = document.createElement('div');
    div.setAttribute('class', 'post block bc2');
    div.innerHTML = html;
    document.getElementById('posts').appendChild(div);

回答by Scott Jones

If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:

如果我理解正确,您正在寻找多行表示,以提高可读性?您想要其他语言中的 here-string 之类的东西。Javascript 可以接近这个:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

回答by ttfreeman

The easiest way to insert html blocks is to use template strings (backticks). It will also allow you to insert dynamic content via ${...}:

插入 html 块的最简单方法是使用模板字符串(反引号)。它还允许您通过 ${...} 插入动态内容:

document.getElementById("log-menu").innerHTML = `
            <a href="#"> 
               ${data.user.email}
            </a>
            <div class="dropdown-menu p-3 dropdown-menu-right">
                <div class="form-group">
                    <label for="email1">Logged in as:</label>
                    <p>${data.user.email}</p>
                </div>
                <button onClick="getLogout()" ">Sign out</button>
            </div>
    `

回答by venki

Add each line of the code to a variable and then write the variable to your inner HTML. See below:

将代码的每一行添加到一个变量中,然后将该变量写入您的内部 HTML。见下文:

var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
var str = "First Line";
str += "Second Line";
str += "So on, all of your lines";
div.innerHTML = str;
document.getElementById('posts').appendChild(div);

回答by raison

If you are using on the same domain then you can create a seperate HTML file and then import this using the code from this answer by @Stano :

如果您在同一个域上使用,那么您可以创建一个单独的 HTML 文件,然后使用@Stano 的这个答案中的代码导入它:

https://stackoverflow.com/a/34579496/2468603

https://stackoverflow.com/a/34579496/2468603