gpt4 book ai didi

jquery - 如何通过ajax将css注入(inject)到文档中?

转载 作者:技术小花猫 更新时间:2023-10-29 11:11:16 25 4
gpt4 key购买 nike

所以我通过jquery的ajax方法获取数据。检索到的数据如下所示:

<html>
<head>
<style>
body {
color: red;
font-weight: bold;
}

#someElement {
color: blue;
padding: 1em
}
</style>
</head>
<body>
<div id="header">Super</div>
<p>blah blah blah</p>
<div id="footer">Stuff</div>
</body>
</html>

如何提取样式并将其插入到正在执行 ajax 调用的当前文档中?我已经尝试了各种 jquery 咒语,但没有成功。我现在通过正则表达式提取 css,但不确定如何将 css 放入当前页面:

$.ajax({
url: '/template.html',
success: function(data) {
$("#header").html( $(data).find('#header').html() );
$("#footer").html( $(data).find('#footer').html() );

var re = /<style>((?:[\n\r]|.)+)<\/style>/m;
var css = re.exec(data);

// What to do with the css??

return;
}
});

我最初有一个样式表,然后简单地执行了以下操作:

    if($.browser.msie) {
$('head').html(
'<link rel="stylesheet" href="http://c.this/template.css" type="text/css" />'+
$('head').html()
);
}
else {
$('head').prepend('<link rel="stylesheet" href="http://c.this/template.css" type="text/css" />');
}

除了在 IE8 中它会导致一些问题外,这有效。

最佳答案

您是否尝试解析第三方页面?

如果不是这种情况,那么为什么不加载独立于调用 ajax 的页面的 CSS。然后它可用于页面上的所有元素 - 甚至是 ajax 提供的新元素。

如果您尝试解析其他站点的页面,则需要开发代理服务。

关于jquery - 如何通过ajax将css注入(inject)到文档中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6522629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com