HTML を含める方法

HTML に HTML フラグメントを含める方法を学ぶ。

HTML

保存する HTML を .html ファイルに含める:

content.html

<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">アニメーション・ボタン</a><br>
<a href="howto_css_modals.asp">モーダル・ボックス</a><br>
<a href="howto_js_animate.asp">アニメーション</a><br>
<a href="howto_js_progressbar.asp">プログレス・バー</a><br>
<a href="howto_css_dropdown.asp">ホバー・ドロップダウン</a><br>
<a href="howto_js_dropdown.asp">ドロップダウンをクリック</a><br>
<a href="howto_css_table_responsive.asp">レスポンシブテーブル</a><br>

HTMLを含めます

を使用して w3-include-html 属性を使用してHTMLを含めます:

<div w3-include-html="content.html"></div>

JavaScriptを追加します

HTMLの含め方はJavaScriptで行われます。

<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /* 全てのHTML要素の集合を巡回します:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /* 特定の属性を持つ要素を検索します:*/
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /* 属性値を使用してファイル名としてHTTPリクエストを送信します:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /* 属性を削除し、この関数を再度呼び出します:*/
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      /* 処理を終了する:*/
      return;
    }
  }
}
</script>

ページの最下部で呼び出します includeHTML()

<script>
includeHTML();
</script>

実際に試してみる

複数のHTMLスライスを含める

任意数のHTMLスライスを含めることができます:

<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>

実際に試してみる