繁体   English   中英

加载ajax响应(html内容数据)而没有CSS冲突

[英]Load ajax response (html content data) without css conflict

1)我有2个不同的域i)www.xxx.xom ii)www.yyy.com

2)然后通过ajax将服务器调用从xxx页发送到yyy页

3)从yyy到xxx页面获取html内容(内容包含带有内联css的html数据)

4)现在我想将响应(html内容)附加到我的DOM中,但没有CSS冲突(这意味着响应内容不受父CSS的影响)

注意:没有IFRAME,有没有可能渲染

样例代码:

 document.onreadystatechange = function () { if (document.readyState == "interactive") { var ajax_response = "<div style='color: blue;'>I m blue </div>"; // sample server reponse document.getElementById("child").innerHTML = ajax_response; } } 
 #parent div { color: red !important; } 
 <div id="parent"> <div>I m red</div> <div id="child"></div> <div>I m red too</div> </div> 

输出:红色将应用于“ I m blue”文本(由于'!important'标签)

如果我没听错,您想设置第一个div的样式,而不是第二个div的样式,这是您的ajax调用产生的。

#parent:first-child {
  color: red !important;
}

这只会影响您的div的第一个div #parent

我得到了这个工作: https : //jsfiddle.net/Twisty/sc6n560t/

HTML

<a id="act" href="">Action</a>

<div id="parent">
  <div>I'm red</div>
  <div id="child"></div>
  <div>Other Text</div>
</div>

CSS

#parent div {
  color: red;
}

div#child.content {
  all: default;
}

JQUERY

$(document).ready(function() {
  $("#act").click(function(e) {
    e.preventDefault();
    var ajax_response = "<div style='color: blue;'>I'm blue </div>"; // sample server reponse
    $("#child").html(ajax_response);
  });
});

在以下问题的更新中找到了此答案: CSS,以防止子元素继承父样式

编辑:CSS工作组由以下方面决定:

div.content { all: default; }

不知道,何时或是否将由浏览器实现。

编辑2:截至2015年3月,除Safari和IE / Edge之外,所有现代浏览器均已实现: https ://twitter.com/LeaVerou/status/577390241763467264(感谢@Lea Verou!)

在您的xxx页面中创建一个div。 将此添加到您的脚本。

$( “#your_div_id”)。追加(response_from_server)

暂无
暂无

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

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