douxian3828 2012-09-18 09:27
浏览 33
已采纳

在特定字符之前和之后为文本字符串着色

I have some data that can only be sorted in specific ways due to the way it's outputted.

I have a table with such text strings as

MyTextString_MyTextString
MyTextString_MyTextString
MyTextString_MyTextString

To make it more readable, I'm looking to color the text before _ red and the text after _ blue. Is this possible with jquery, or php?

I have tried things such as $('.myElement').find('_').css('color','red); but don't think that is the right approach.

Is it possible to only do this once, such as if there is another text string it will remain the second color, blue? i.e. Red_Blue_Blue_Blue (Count = 1?)

Example of markup.

<td class="myTextString1">
    MyTextString_MyTextString1
    <br/>
    MyTextString_MyTextString2
    <br/>
    MyTextString_MyTextString3
</p>
  • 写回答

3条回答 默认 最新

  • doujiao3346 2012-09-18 10:04
    关注

    js:

    var colorize = function(text) {
      var delimiter = "_",
          parts = text.split(delimiter),
          firstPart = $("<span>", { class: 'red', html: parts[0] }),
          secondPart = $("<span>", { class: 'blue', html: text.split(parts[0] + delimiter)[1] });
    
      return $("<div>").append(firstPart).append(delimiter).append(secondPart).html();
    }
    

    edit: You could also utilize a helper function that takes jQuery elements like this:

    var colorizeElements = function($elements) {
      // $elements has to be something like $("td.classname")
      $elements.each(function() {
        $(this).html(colorize($(this).html()));
      });
    };
    

    edit: working jsFiddle: http://jsfiddle.net/tGV54/1/

    edit: based on Kristoffers code:

    String.prototype.colorize = function () {
        var regex = new RegExp('[^_]+', 'gi'),
            color = $.extend(['blue', 'red'], arguments || []),
            index = 0;
    
        return this.replace(regex, function(matched) {
            return '<span style="color: ' + color[index++] + ';">' + matched + '</span>';
        });
    };
    
    $.fn.customColorize = function () {
        var args = arguments,
            delimiter = "<br>";
    
        return this.each(function () {
            var splitetElements = $.map(this.innerHTML.split(delimiter), function(s) { return s.colorize(); });
            this.innerHTML = splitetElements.join(delimiter);
        });
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作