javascript - 如何使用 javascript 函数重用 HTML 代码块?

标签 javascript jquery html css optimization

我尝试在多个位置和页面中使用相同的 HTML block ,同时保持较少的代码行数和较低的冗余度。

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

我不想使用 PHP include。

例子:

<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

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>

可重用文件.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 - 如何使用 javascript 函数重用 HTML 代码块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093849/

相关文章:

html - 定位页面上的特定 h2

php - 获取非英语的用户输入

javascript - 绘制不影响力导向图物理的链接

javascript - 我该如何修复这个 javascript 函数?

jquery - 仅当用户一直向上滚动时显示 div

javascript - 仅在单击父项后打开子菜单

javascript - 如何在 JavaScript 中将 "range"的值转换为 float ?

javascript - Firestore 初始更新无法识别。为什么?

javascript - 通过 javascript 使用来自 ajax 的数据填充 <select>

java - 如何提取jsoup中的下一个标签元素