如何将一段 html 代码分配给一个 javascript 变量

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

how to assign a block of html code to a javascript variable

javascripthtml

提问by jamex

what is the syntax to store a block of html code to a javascript variable?

将 html 代码块存储到 javascript 变量的语法是什么?

<div class='saved' >
<div >test.test</div> <div class='remove'>[Remove]</div></div>

I want to assign the above code to a variable 'test'

我想将上面的代码分配给变量“test”

var test = "<div class='saved' >
<div >test.test</div> <div class='remove'>[Remove]</div></div>";

but it does not work, which are the correct syntax for assigning the code?

但它不起作用,分配代码的正确语法是什么?

TIA

TIA

采纳答案by draganHR

 var test = "<div class='saved' >"+
 "<div >test.test</div> <div class='remove'>[Remove]</div></div>";

You can add "\n" if you require line-break.

如果需要换行,可以添加“\n”。

回答by Brian Ayers

Greetings! I know this is an older post, but I found it through Google when searching for "javascript add large block of html as variable". I thought I'd post an alternate solution.

你好!我知道这是一篇较旧的帖子,但我在搜索“javascript add large block of html as variable”时通过谷歌找到了它。我以为我会发布一个替代解决方案。

First, I'd recommend using single-quotes around the variable itself ... makes it easier to preserve double-quotes in the actual HTML code.

首先,我建议在变量本身周围使用单引号......更容易在实际的 HTML 代码中保留双引号。

You can use a backslash to separate lines if you want to maintain a sense of formatting to the code:

如果您想保持代码的格式感,可以使用反斜杠来分隔行:

var code = '<div class="my-class"> \
        <h1>The Header</h1> \
        <p>The paragraph of text</p> \
        <div class="my-quote"> \
            <p>The quote I\'d like to put in a div</p> \
        </div> \
    </div>';

Note: You'll obviously need to escape any single-quotes inside the code (e.g. inside the last 'p' tag)

注意:您显然需要对代码中的任何单引号进行转义(例如在最后一个 'p' 标签中)

Anyway, I hope that helps someone else that may be looking for the same answer I was ... Cheers!

无论如何,我希望能帮助那些可能正在寻找与我相同答案的人......干杯!

回答by Bharath Kumar

we can use backticks (``) without any error.. eg: <div>"test"<div>

我们可以使用反引号 (``) 而不会出现任何错误.. 例如: <div>"test"<div>

we can store large template(HTML) inside the backticks which was introduced in ES6 javascript standard

我们可以在 ES6 javascript 标准中引入的反引号中存储大模板(HTML)

No need to escape any special characters

无需转义任何特殊字符

if no backticks.. we need to escape characters by appending backslash() eg:" \"test\""

如果没有反引号……我们需要通过附加反斜杠()来转义字符,例如:"\"test\""

回答by Alireza Fattahi

I recommend to use mustachetemplating frame work. https://github.com/janl/mustache.js/.

我建议使用mustache模板框架工作。https://github.com/janl/mustache.js/

<body>
       ....................
       <!--Put your html variable in a script and set the type to "x-tmpl-mustache"-->
       <script id="template" type="x-tmpl-mustache">
           <div class='saved' >
           <div >test.test</div> <div class='remove'>[Remove]</div></div>
    </script>
</body>

  //You can use it without jquery.
  var template = $('#template').html();
  var rendered = Mustache.render(template);
  $('#target').html(rendered);

Why I recommend this?

为什么我推荐这个?

Soon or latter you will try to replace some part of the HTML variable and make it dynamic. Dealing with this as an HTML Stringwill be a headache. Here is where Mustache magic can help you.

迟早您将尝试替换 HTML 变量的某些部分并使其动态化。String将其作为 HTML 处理将是一件令人头疼的事情。这里是 Mustache 魔法可以帮助你的地方。

<script id="template" type="x-tmpl-mustache">
 <div class='remove'>  {{ name }}! </div> ....
</script>

and

 var template = $('#template').html();
 // You can pass dynamic template values
  var rendered = Mustache.render(template, {name: "Luke"});
  $('#target').html(rendered);

There are lot more features.

还有很多功能。

回答by Mike S.

Modern Javascript implementations with the templatesyntax using backticks are also an easy way to assign an HTML block of code to a variable:

template使用反引号语法的现代 Javascript 实现也是一种将 HTML 代码块分配给变量的简单方法:

    const firstName = 'Sam';
    const fullName = 'Sam Smith';
    const htmlString = `<h1>Hello ${fullName}!</h1><p>This is some content \
        that will display. You can even inject your first name, ${firstName}, \
        in the code.</p><p><a href="http://www.google.com">Search</a> for \
        stuff on the Google website.</p>`;

回答by mim

Just for reference, here is a benchmark of different technique rendering performances,

仅供参考,这里是不同技术渲染性能的基准,

http://jsperf.com/zp-string-concatenation/6

http://jsperf.com/zp-string-concatenation/6

m,

米,

回答by whiskey 4

you can make a javascript object with key being name of the html snippet, and value being an array of html strings, that are joined together.

您可以创建一个 javascript 对象,键是 html 片段的名称,值是一个 html 字符串数组,它们连接在一起。

var html = {
  top_crimes_template:
    [
      '<div class="top_crimes"><h3>Top Crimes</h3></div>',
      '<table class="crimes-table table table-responsive table-bordered">',
        '<tr>',
          '<th>',
            '<span class="list-heading">Crime:</span>',
          '</th>',
          '<th>',
            '<span id="last_crime_span"># Arrests</span>',
          '</th>',
        '</tr>',
      '</table>'
    ].join(""),
  top_teams_template:
    [
      '<div class="top_teams"><h3>Top Teams</h3></div>',
      '<table class="teams-table table table-responsive table-bordered">',
        '<tr>',
          '<th>',
            '<span class="list-heading">Team:</span>',
          '</th>',
          '<th>',
            '<span id="last_team_span"># Arrests</span>',
          '</th>',
        '</tr>',
      '</table>'
    ].join(""),
  top_players_template:
    [
      '<div class="top_players"><h3>Top Players</h3></div>',
      '<table class="players-table table table-responsive table-bordered">',
        '<tr>',
          '<th>',
            '<span class="list-heading">Players:</span>',
          '</th>',
          '<th>',
            '<span id="last_player_span"># Arrests</span>',
          '</th>',
        '</tr>',
      '</table>'
    ].join("")
};