简体   繁体   English

使用 AJAX 加载外部 HTML 文件时忽略 CSS

[英]Ignore CSS when loading external HTML file with AJAX

I am building a webpage and I am using a javascript function to get an HTML file and show the content of it.我正在构建一个网页,我正在使用 javascript function 来获取 HTML 文件并显示它的内容。

http://progress.cat/portfolio.html -> where main HTML is http://progress.cat/portfolio.html -> 其中主要的 HTML 是

http://progress.cat/portfolio_js.html -> getting HTML from this page (to be placed in portfolio.html) http://progress.cat/portfolio_js.html -> 从此页面获取 HTML(放置在portfolio.html中)

The problem is my portfolio.html main CSS问题是我的投资组合。html 主要 CSS

http://progress.cat/assets/css/particle_dark.css http://progress.cat/assets/css/particle_dark.css

http://progress.cat/assets/css/particle_demo.css http://progress.cat/assets/css/particle_demo.css

is being mixed with my portfolio_js.html css正在与我的投资组合_js.html css

http://progress.cat/portfolio_logic/css/freelancer.min.css http://progress.cat/portfolio_logic/css/freelancer.min.css

What I want is portfolio_js to ignore the main CSS我想要的是portfolio_js忽略主要的CSS

How it looks它看起来如何

How it should look它应该是什么样子

Is this possible?这可能吗?

Function : Function

  function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};

First of all, I'd recommend you include this partial snippet on the server-side rather than with ajax.首先,我建议您在服务器端包含这个部分片段,而不是 ajax。 For example, if you're using PHP, it would be like: <?php include 'some_file.html'; ?>例如,如果您使用 PHP,它会像: <?php include 'some_file.html'; ?> <?php include 'some_file.html'; ?>

But if you're going to use ajax, then the external file you want to get should not include anything except for the raw HTML you're trying to get.但是,如果您要使用 ajax,那么您想要获取的外部文件不应包含任何内容,除了您尝试获取的原始 HTML。 It shouldn't have any other tags.它不应该有任何其他标签。 No <html> , <head> , etc. Any stylesheets it needs should be loaded onto the main page.没有<html><head>等。它需要的任何样式表都应该加载到主页上。

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

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