使用JS获取外部HTML文件时部分Div元素丢失的问题排查
问题:导入header.html时部分div元素丢失
我正尝试将/layout文件夹中的header.html导入到index.html中,操作可执行,但部分div元素丢失——返回数据里缺少带有“test2”和“test3”文本的div。
我试过两种实现方式,都没解决问题:
- jQuery方案:执行
$("#headerPlaceHolder").load("./layout/header.html");,无法正常工作 - 自定义XMLHttpRequest模块:代码如下,执行后打印responseText仍存在元素丢失情况
自定义模块代码:
(function (w) { var importFileModule = function () {}; window.defaultImage = "../assets/images/placeholder.png"; importFileModule.constructor = importFileModule; importFileModule.prototype = { init: function () { var z, i, elmnt, file, xhttp; z = document.getElementsByTagName("*"); for (i = 0; i < z.length; i++) { elmnt = z[i]; file = elmnt.getAttribute("import-file-path"); if (file) { xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200) { elmnt.innerHTML = this.responseText; console.log('import file success'); console.log(this.responseText); } if (this.status == 404) { elmnt.innerHTML = "Page not found."; } elmnt.removeAttribute("import-file-path"); $importFileModule.init(); } }; xhttp.open("GET", file, true); xhttp.send(); return; } } }, }; w.$importFileModule = new importFileModule(); $importFileModule.init(); })(window);
目前问题未解决,但已找到替代方案:
内容的提问来源于stack exchange,提问作者sawacrow
相关产品推荐
相关产品推荐

