如何使用jQuery为特定的代码行着色?
例如,以//
开头的所有行都需要为绿色。
<pre class="code">
//I need to color this line
Some code
//This line should also be colored
More code
</pre>
答案 0 :(得分:3)
尝试这样的事情,
\n
//
//
在那里,则用首选样式<强>样本强>
$('.code').html(function(i, val) {
return $.map(val.split("\n"), function(v, i) {
var match = v.match(/\s*\/\//);
if (match != null)
if (v.indexOf(match[0]) == 0)
return '<span style="color:green">' + v + '</span>';
return v;
}).join("\n");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<pre class="code">
//I need to color this line
Some code
//This line should also be colored
More code
//........
..... //........
//.......
</pre>
答案 1 :(得分:0)
你需要使用JQuery吗?为什么不使用CSS?
<span style="color:green;">//I need to color this line</span>
答案 2 :(得分:0)
CSS最适合颜色。它速度快,可以推广。 到处使用同一个班级。只需用你的颜色在CSS中添加该类。
这是一个例子。
<pre class="code">
<p class="green">
Some code
</p>
<p class="black">
Some code
</p>
</pre>
现在在CSS中添加此代码
.green{
color:green;
}
.black{
color:black;
}
多数民众赞成。
答案 3 :(得分:0)
我设法让它像这样工作:
var str = $(".code").html();
str = str.replace(/\/\/([a-zA-Z ]+)/g, function replaceFunction(value) { return "<span style=\"color: Green;\">" + value + "<span>"; }));
答案 4 :(得分:0)
从pre
标记中获取文字。遍历所有行,如果它们以//
开头,则将其包含在span标记中。用css调整跨度。请注意,样式代码中有许多(jequery)插件。没有必要重新发明轮子。
var lines = $('pre.code').text().split('\n');
var formatted="";
$.each(lines, function(){
if(this.trim().substring(0, 2)=='//'){
formatted+='<span>'+this+'</span>';
}
else{
formatted+=this;
}
});
$('pre.code').html(formatted);