所以我通過jquery的ajax方法獲取數據。檢索的數據如下所示:如何通過ajax將css注入到文檔中?
<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中引起一些問題。
它看起來像你的jQuery選擇器正在尋找一個元素帶有「head」標識。你可能想用'$(「head」)。html($(data).find(「head」)。html());' –
@josh那部分工作正常。我只是更新了這個例子,所以它說#header而不是#head只是爲了表明我對head元素不感興趣。謝謝。 – PaulS