Cách bao gồm HTML

Học cách bao gồm đoạn HTML trong HTML.

HTML

Sẽ chứa HTML lưu vào tệp .html:

content.html

<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">Animated Buttons</a><br>
<a href="howto_css_modals.asp">Modal Boxes</a><br>
<a href="howto_js_animate.asp">Animations</a><br>
<a href="howto_js_progressbar.asp">Progress Bars</a><br>
<a href="howto_css_dropdown.asp">Hover Dropdowns</a><br>
<a href="howto_js_dropdown.asp">Nhấp vào danh sách rơi</a><br>
<a href="howto_css_table_responsive.asp">Bảng phản hồi</a><br>

bao gồm HTML

Sử dụng w3-include-html thuộc tính để bao gồm HTML:

Mô hình

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

Thêm JavaScript

Bao gồm HTML được hoàn thành bằng JavaScript.

Mô hình

<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /* Duyệt qua bộ sưu tập tất cả các phần tử HTML: */
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /* Tìm kiếm phần tử có thuộc tính đặc định: */
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /* Sử dụng giá trị thuộc tính làm tên tệp để gửi yêu cầu 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 = "Trang không tìm thấy.";}
          /* Xóa thuộc tính và gọi lại hàm này: */
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      /* Thoát hàm: */
      return;
    }
  }
}
</script>

Gọi từ cuối trang includeHTML():

Mô hình

<script>
includeHTML();
</script>

Thử trực tiếp

Bao gồm nhiều đoạn mã HTML

Bạn có thể bao gồm bất kỳ số lượng đoạn mã HTML nào:

Mô hình

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

Thử trực tiếp