繁体   English   中英

用 VanillaJS 而不是 jQuery 将 div 替换为另一个 html 文件('common/...html)的内容

[英]Replacing a div with the content of another html-file ('common/…html) with VanillaJS instead of jQuery

我希望能够编写以下内容,而无需导入 jQuery 库,以便将 div 替换为另一个 html 文件中编写的组件的内容:

 <head> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <script> $.get("common/navbar.html", function(data) { $("#navbar-placeholder").replaceWith(data); }); </script> <div id="navbar-placeholder"></div> </body>

很乐意提出建议

您可以像下面那样做,您可能需要根据您的要求进行更改。

fetch('common/navbar.html')
  .then(response => {
     var el = document.getElementById('navbar-placeholder');
     el.insertAdjacentHTML('afterbegin', response);
  })

这里的response需要是 HTML。

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

我尝试了Gowtham Raj J建议的fetch ,但它没有立即工作。 但是第二个.then在第一个响应之后链接它运行良好:

fetch('common/navbar.html')
    .then(res => {
      return res.text();
    })
    .then(cont => {
      var navPlaceholder = document.getElementById('navbar-placeholder');
      navPlaceholder.insertAdjacentHTML('afterbegin', cont);
    });

暂无
暂无

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

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