【问题标题】:How can I reuse HTML code blocks using a javascript function?如何使用 javascript 函数重用 HTML 代码块?
【发布时间】:2016-05-07 17:43:58
【问题描述】:

我试图在多个地方和页面中使用相同的 HTML 块,同时保持低代码行数和低冗余。

基本上,我需要类似于函数的东西,当它被调用时,它只会将 HTML 代码加载到页面中 - 这将在页面加载时完成,因此无需单击或其他需要触发它的操作。

我不想使用 PHP 包含。

例子:

<div class="x">
   <div class="y">
      <div class="z"></div>
   </div>
</div>

我需要在 100 多个页面中使用相同的 X 类,并且它将具有相同的内容。

仅插入 X 类和要自动添加的内部内容的最佳方法是什么?

【问题讨论】:

  • 在我看来,如果你想包含 html 并且你正在使用 PHP,只需使用 include 命令。它将包括 HTML。如果是静态 HTML,则不会进行解析。如果是PHP,会被解析为PHP。与调用函数相比,它的开销要少得多。
  • 为什么不把它设置在头部作为变量(javascipt)
  • 查看使用“视图助手”、“部分”等的框架。模板引擎也有一些想法。尽管本质上它所有的“包含”都在下面。如果它没有坏,请不要修复它。
  • 我想,你会在这里找到答案stackoverflow.com/questions/17420146/…
  • 考虑任何“模板”技术,例如blog.reybango.com/2010/07/12/…

标签: javascript jquery html css optimization


【解决方案1】:

如果你不介意使用肮脏的方式,试试这个。 :)

$(".reuseTarget").html($(".x").text());

$(".reuseTarget").html($(".x").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="x">
   <div class="y">
      <div class="z">aabb</div>
   </div>
</div>

<div class="reuseTarget">
  </div>

【讨论】:

    【解决方案2】:

    如果您正在使用任何 javascript 框架,它们通常也有一个选项。

    AngularJS 使用指令来处理重复的 html 代码。 https://docs.angularjs.org/guide/directive

    还可能重复以下问题: How to reuse the html code in every html page?

    【讨论】:

      【解决方案3】:

      您可以将您的代码放在不同的 .html 文件中并使用 .load() http://api.jquery.com/load/ 加载它

      $('#targetid').load('somewhere/a.html'); // loads the .html in the #targetid
      

      ma​​in.html

      <!DOCTYPE HTML>
      <html>
          <head>
              <meta charset="UTF-8">
              <title>Main page</title>
              <sript src="http://code.jquery.com/jquery-latest.js"></script>
              <script>
                   $(function(){
                        $('#commonsection').load('reusablefile.htm');
      
                        // which is eqvivalent to:
                        //
                        // $.ajax({
                        //     url: 'reusablefile.htm',
                        //     dataType: 'html',
                        //     success: function(data){
                        //         $('#commonsection').html(data);
                        //     }
                        // });
                   });
              </script>
           </head>
           <body>
               <div id="commonsection"></div>
           </body>
      </html>
      

      reusablefile.html:

      <script>
          (function($){ //separate scope to keep everything "private" for each module
              //do additional javascript if required
          })(jQuery);
      </script>
      <p>...Some non-trivial content...</p>
      

      【讨论】:

        猜你喜欢
        • 2012-11-13
        • 1970-01-01
        • 2019-09-16
        • 1970-01-01
        • 1970-01-01
        • 2017-08-01
        • 2021-04-25
        • 2015-03-14
        • 1970-01-01
        相关资源
        最近更新 更多