简体   繁体   English

使用 HTML 和 JS 将 HTML 从一个文件导入另一个文件?

[英]Import HTML from one file to another using HTML and JS?

I have tried a few different solutions both on here and from various sources around the web but nothing seems to work.我在这里和 web 周围的各种来源都尝试了一些不同的解决方案,但似乎没有任何效果。 iframes seem to grab the test pdf file i have and use it instead of the html (i plan on using the iframe pdf viewer) iframes seem to grab the test pdf file i have and use it instead of the html (i plan on using the iframe pdf viewer)

jQuery and js script tags seem to have no effect jQuery和js脚本标签好像没有效果

I'm using freshly installed Firefox so js is enabled.我正在使用新安装的 Firefox 所以启用了 js。

The way im testing is by opening the html file so do i need to open the web page some other way?即时测试的方式是打开 html 文件,所以我需要以其他方式打开 web 页面吗?

I'm just looking to have my title and navbar on all my pages while only having to update one file.我只是想在我的所有页面上都有我的标题和导航栏,而只需要更新一个文件。 if anyone has any other solutions i would love to try them.如果有人有任何其他解决方案,我很想尝试一下。

Thanks in advance.提前致谢。

Try the solution i found: https://github.com/louisho5/jQuery-Include-HTML-File-Plugin This will let you include another html page inside your current html page using jquery. Try the solution i found: https://github.com/louisho5/jQuery-Include-HTML-File-Plugin This will let you include another html page inside your current html page using jquery.

You can also accomplish what you're trying to achieve using php include, but requires your app to run on a web server:您还可以使用 php 包括来完成您想要实现的目标,但需要您的应用程序在 web 服务器上运行:

Add the this tag inside the body of your page <?php include 'navigation.php';?>在页面正文中添加这个标签<?php include 'navigation.php';?>

See: https://www.w3schools.com/php/php_includes.asp见: https://www.w3schools.com/php/php_includes.asp

My solution so far is:到目前为止,我的解决方案是:

function renderImportContent() {
    //get template element and clone to clon
    var templateList = document.body.querySelectorAll("div[import]");
    //run throught the list and replace elements with templates
    for (var i = 0; i < templateList.length; i++) {
        //console.log(templateList[i].innerHTML);
        templateList[i].outerHTML = fetchTemplate(templateList[i].getAttribute("import"))
    }
}

function fetchTemplate(path) {
    console.log('/html/template/'.concat(path));
    fetch('/html/template/'.concat(path)).then((response) =>{ return response.text();}).then((html) => { document.body.innerHTML = html}).catch((error) => {console.log("fetch error:", err)});
}

With the only issue seeming to be that it removes more than it should.唯一的问题似乎是它删除的内容超出了应有的范围。 Instead of replacing the inside of the div tag it replaces the entire body.它不会替换 div 标签的内部,而是替换整个正文。

I've tried using textContent as well but that also didn't work.我也尝试过使用 textContent ,但这也没有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM