How can I get CSS comments with jQuery?

混江龙づ霸主 提交于 2019-12-06 05:20:48

问题


I am wondering how I can read CSS comments out of a linked stylesheet.

I have this sample CSS loaded via:

<link rel="stylesheet" type="text/css" media="all" href="test.css" />

 

#test1{ border:1px solid #000; }
#test2{ border:1px solid #000; }
#test3{/* sample comment text I'm trying to read */}

I'm testing this in FF3. The following javascript reads the rules but doesn't read the comments in#test3.

window.onload = function(){
    s=document.styleSheets;
    for(i=0;i < s[0].cssRules.length;i++){
        alert(s[0].cssRules[i].cssText);
    }
}

回答1:


You could retrieve the stylesheet's contents and use regex to parse the comments. This example uses jQuery to get the stylesheet text and a regular expression to find the comments:

jQuery.get("test.css", null, function(data) {
    var comments = data.match(/\/\*.*\*\//g);
    for each (var c in comments) 
        alert(c);
});

You could also find the stylesheet links using selectors.




回答2:


Comments will almost always be ignored by an interpreter and therefor will not be available.




回答3:


You can access the CSS file using an AJAX query and then parse the results yourself looking for comments. The interpreter won't get in the way then.

As long as the CSS is on the same domain as the page, this will work nicely.




回答4:


You can't, that's the entire point of comments.




回答5:


You can't read the CSS file JavaScript, just inspect the results in the DOM. One possible way might be to use an embedded stylesheet, where you can query the textual content of the style tag via the DOM interface. You have to parse the content for yourself, of course.



来源:https://stackoverflow.com/questions/401668/how-can-i-get-css-comments-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!