[英]HTML include using ajax - how to access the included files elements?
我最近設法解決了我自己的問題: 更改所選 <li> 的顏色
但是現在我遇到了一個新問題 - 自從解決了上述問題后,我想更改我的 html 文件,以便它們不都定義相同的頂部橫幅、菜單導航和頁腳代碼,這似乎是在浪費空間。
所以我使用 Ajax 來有效地包含我需要的 html 文件,所以現在我的每個 html 文件在頁面的頂部和底部都有一個頁眉和頁腳元素,下面的 ajax 代碼用單獨的 html 文件填充這些頁眉和頁腳元素:
$(document).ready(function () {
fetch("./header.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./footer.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
});
問題是現在解決我之前問題的代碼(鏈接到本問題開頭)不起作用,這是代碼:
$(document).ready(function () {
var path = window.location.pathname.substring(1);
path = path.substring(0, path.length - 5);
var pathShort = path.substring(path.indexOf("/")+1);
var activeLink = document.getElementById(pathShort);
activeLink.classList.add("active");
});
我相信“document.getElementById(pathShort);” call 不再有效,因為從技術上講,id 等於 pathShort 的元素不再在該頁面上(不在文檔中),而是在 ajax 包含的 header.html 中。
所以我的問題是,如何在調用“document.getElementById(pathShort);”時在包含的 header.html 文件中進行搜索?
我相信“document.getElementById(pathShort);” call 不再有效,因為從技術上講,id 等於 pathShort 的元素不再在該頁面上(不在文檔中),而是在 ajax 包含的 header.html 中。
這是因為當您調用getElementById
時它不在頁面中。
它將在您使用innerHTML
分配之后
因此,在使用innerHTML
分配代碼后,將代碼移動到某個點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.