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();
}
编辑:您还可以使用一个辅助函数,它采用这样的 jQuery 元素:
var colorizeElements = function($elements) {
// $elements has to be something like $("td.classname")
$elements.each(function() {
$(this).html(colorize($(this).html()));
});
};
编辑:工作 jsFiddle:http: //jsfiddle.net/tGV54/1/
编辑:基于 Kristoffers 代码:
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);
});
};