How can I get CSS comments with jQuery?

2020-07-18 10:42发布

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);
    }
}

5条回答
Melony?
2楼-- · 2020-07-18 11:20

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.

查看更多
神经病院院长
3楼-- · 2020-07-18 11:29

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.

查看更多
甜甜的少女心
4楼-- · 2020-07-18 11:33

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.

查看更多
forever°为你锁心
5楼-- · 2020-07-18 11:37

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

查看更多
\"骚年 ilove
6楼-- · 2020-07-18 11:41

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

查看更多
登录 后发表回答