我在一个项目中工作,现在我需要做一些我不知道的事情。我想给<td>内的文本中的特定单词(关键字)上色
我可以做静态,因为文本是随机的,它们来自数据库。
这是一个普通的文本,我想给像“动物,宠物”这样的单词上色。并为每个字体设置特定的颜色,例如,动物爱好者喜欢红色,宠物喜欢蓝色字体颜色。
我想我必须使用Jquery来处理它,并在页面加载后创建一个函数来完成它(readyFunction)。
但是我没有任何想法去做,我对jquery是新手。你能给我一些建议吗?
谢谢!
发布于 2017-02-10 01:18:43
这确实是一个“肮脏”的解决方案,但它将作为如何处理任务的示例:
<body>
<table id="the_table">
<tr>
<td>random words from DB: like an apple, pet, whatever, yet another apple</td>
</tr>
</table>
<script>
$(document).ready(function () {
var content_cell,
random_words = "",
colors_map = {
"apple": "red",
"pet": "blue"
};
// selector for your specific table cell
$('#the_table tr').each(function() {
content_cell = $(this).find("td:first");
});
// get cell content
random_words = content_cell.html();
// replace your keywords according the map
$.each(colors_map, function( index, value ) {
random_words = random_words.replace(new RegExp(index, 'g'), "<font color='" + value + "'>" + index + "</font>");
});
// set back html content into the cell
content_cell.html(random_words);
});
</script>
</body>发布于 2017-02-10 02:05:56
假设您的浏览器支持html5,不需要JQuery,请尝试以下代码:
function renderKey(){
//create color list in case you don't want to get invisible color such as 'white' from random color..
// make the list long enough to avoid duplicated color
var colors = ['red', 'blue', 'orange', 'cyan', 'black'];
var keyColor = {};
var keyIndex = 0;
//you may need more selectors to exclude unexpected elements, e.g. <td> in <thead>.
var x = document.querySelectorAll("td");
for (i in x){
//suppose your key words seperated by ',' in <td>
var keyWords = x[i].innerHTML.split(',');
x[i].innerHTML = keyWords.reduce(
function(total, value, index){
return total + '<span style="color:' +
(keyColor[value] || (keyColor[value] = colors[ keyIndex++ % colors.length])) +
'">' + value + '</span>';
},
''
);
}
}https://stackoverflow.com/questions/42141760
复制相似问题