【问题标题】:how to assign a block of html code to a javascript variable如何将一段 html 代码分配给 javascript 变量
【发布时间】:2010-08-04 22:02:32
【问题描述】:

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

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

我想把上面的代码赋值给一个变量'test'

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

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

TIA

【问题讨论】:

  • 究竟是什么不起作用?你不能在那里换行,但除此之外语法很好。
  • 谢谢 Cfreak,换行是问题
  • 那么如果你缩小你的html,它可以放在一个字符串中吗?

标签: javascript html


【解决方案1】:

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

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

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

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>';

注意:您显然需要转义代码中的任何单引号(例如,在最后一个“p”标签内)

无论如何,我希望这对可能正在寻找与我相同的答案的其他人有所帮助......干杯!

【讨论】:

  • 在使用这种插入额外空格的方法时要小心。尤其是如果这个 javascript 是严重嵌套的。
  • @BrianAyers 我们如何在这里插入条件语句?
【解决方案2】:
 var test = "<div class='saved' >"+
 "<div >test.test</div> <div class='remove'>[Remove]</div></div>";

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

【讨论】:

  • 感谢 Dragan,这是 html 文本代码中的 2 个换行符。
  • 为什么在 HTML 中使用单引号?
  • @ram4nd I c/p code from post,但你是对的,'&lt;div class="saved"&gt;'... 会更好。
  • "如果需要换行,可以添加"\n"。"你可以吗?根据这个答案stackoverflow.com/a/5125874/719457你不能。
  • 双引号中的单引号呢?即&lt;a onclick="return someFunc('x');"&gt;Click Me&lt;/a&gt;
【解决方案3】:

我们可以使用反引号 (``) 而不会出现任何错误。例如:&lt;div&gt;"test"&lt;div&gt;

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

无需转义任何特殊字符

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

【讨论】:

  • 这是 2017 年的绝佳答案。更多信息可以在 MDN here. 上找到
  • 这是我整个星期学到的最好的东西。我只是......它......太漂亮了!
  • 这对我来说是个不错的解决方案,但 IE11 不支持模板文字,caniuse.com/#feat=template-literals
  • 确实很棒!!这在 HTML 代码来自其他来源时非常有用。谢谢
  • 哇,这拯救了我的一天!非常感谢,我不知道我们可以使用反引号!
【解决方案4】:

我建议使用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);

我为什么推荐这个?

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

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

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

还有更多功能。

【讨论】:

    【解决方案5】:

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

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

    米,

    【讨论】:

      【解决方案6】:

      使用反引号的 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>`;
      

      【讨论】:

        【解决方案7】:

        您可以创建一个 javascript 对象,其中键是 html sn-p 的名称,值是连接在一起的 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("")
        };
        

        【讨论】:

          【解决方案8】:

          请在您的html字符串的前后使用符号反引号'`',这就是所谓的模板文字,现在您可以在多行中编写纯html并分配给变量。

          示例>>

          var htmlString =
          
          `
          
          <span>Your</span>
          <p>HTML</p>
          
          `
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-05-31
            • 1970-01-01
            • 1970-01-01
            • 2017-06-09
            相关资源
            最近更新 更多