简体   繁体   English

jQuery根据文本更改颜色

[英]jquery change color depending on the text

i have a log file which look like this loaded to page: 我有一个日志文件,看起来像这样加载到页面:

23-06-2013, 15:04 - Action no.11
-Ip adress ::1
23-06-2013, 15:04 - Error no.21
-Ip adress ::1

and i wanna change color of those Action no.11 and Error no.21 with jquery (hope it is possible). 我想用jQuery更改那些动作11和错误21的颜色(希望是可能的)。 Action should be one color (eg green) and Error should be other one (eg Red). 动作应为一种颜色(例如,绿色),错误应为另一种颜色(例如,红色)。 It is loaded from .log file so it has no tags like . 它是从.log文件加载的,因此没有类似的标签。 So i think, it should check for word "Action" or "error" and change color. 所以我认为,它应该检查单词“ Action”或“ error”并更改颜色。 thx for advice 寻求建议

  • insert your log to .log , for example to <pre> (it will be nicer if JS is disabled): 将日志插入.log ,例如<pre> (如果禁用JS会更好):

HTML : HTML

<pre class="log">23-06-2013, 15:04 - Action no.11
-Ip adress ::1
23-06-2013, 15:04 - Error no.21
-Ip adress ::1</pre>
  • split lines to array 将行分割为数组
  • clear .log 清除.log
  • loop lines 循环线
  • wrap text to jQuery object 将文本包装到jQuery对象
  • append to .log 附加到.log
  • check if line contains Action or Error 检查行是否包含ActionError
  • change color 换颜色

jQuery : jQuery的

var lines = $('.log').text().split('\n');
$('.log').empty();

$.each(lines, function() {
    var $this = $('<div>'+this+'</div>');

    $('.log').append($this);
    if( $this.text().match('Action') ) {
        $this.css('color', 'green');
    }
    else if( $this.text().match('Error') ) {
        $this.css('color', 'red');
    }
});

jsFiddle 的jsfiddle

This is kinda like syntax highlighting 这有点像语法突出显示

function makeSpan(match){
    var color; 
    if(match.match('Error')){
    color = "red";
       }
       else{
       color = "green";
       }
    return "<span style='color:"+color+"'>"+ match  +"</span>";
}

var body = $('body');
var newBody = body.html().replace(/(Action.+)|(Error.+)/g,makeSpan);
body.html(newBody);

Chek out this jsFIddle 检查这个jsFIddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM