如何使用 JavaScript 函数重用 HTML 代码块

How can I reuse HTML code blocks using a javascript function?

本文关键字:HTML 代码 何使用 JavaScript 函数      更新时间:2023-09-26

我正在尝试在多个地方和页面使用相同的HTML块,同时保持少量代码和低冗余。

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

我不想使用 PHP 包含。

例:

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

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

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

您可以将

代码放在不同的.html文件中,并加载.load() http://api.jquery.com/load/

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

主.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>

可重用文件.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>

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

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

也可能重复以下问题:如何在每个 html 页面中重用 html 代码?

如果您不介意使用肮脏的方式,请尝试此操作。 :)

$(".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>