[英]Extrating embedded styles from an HTML page with JQuery
So, here's the problem... 所以,这就是问题所在...
I have to: 我必须:
Therefore the parts of the page that I'm interested in are: 因此,我感兴趣的页面部分是:
<style>
#tableid td.someclass {
...
}
#tableid td.anotherclass {
...
}
[etc etc ..]
</style>
And 和
<table id="tableid">
...
</table>
So, going through the list above 1,2 & 4 are no problem at all. 因此,遍历1,2和4之上的列表完全没有问题。 It's 3 and 5 that are taxing the brain - there are no external stylesheets to worry about BTW, everything is in the page that I'm grabbing inside a single tag. 是3和5令人费解-没有外部样式表可以担心BTW,所有内容都在我抓到的单个标签内。
I guess I could extract the entire element and then append it to my page - but that is messy and could result in unwanted side-effects. 我想我可以提取整个元素,然后将其附加到我的页面上-但这很杂乱,并可能导致不良的副作用。 What I'd like to do is just extract the styling that applies to #tableid and then apply them the table appended to my div. 我想做的只是提取适用于#tableid的样式,然后将附加到我的div的表应用于它们。
Is there an elegant way to do that? 有没有一种优雅的方法可以做到这一点?
You could pull the styles from the header using a standard jQuery finder: 您可以使用标准的jQuery查找器从标题中提取样式:
var styles = $('head style').text();
Then run a regular expression against it: 然后对它运行一个正则表达式:
var tableID = 'tableid',
pattern = new RegExp('#'+ tableID + '[^}]+}', 'g'),
tableStyles = styles.match(pattern);
This should give you an array of styles for your table's id. 这应该为您的表ID提供一系列样式。 Now you can append these styles to your current document's head: 现在,您可以将这些样式附加到当前文档的头部:
$('<style/>', { text: tableStyles.join('\n') }).appendTo('head');
Your use case might require some fine–tuning, but this should approximately give you what you're after. 您的用例可能需要进行一些微调,但这应该可以大致满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.