首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对<td>中的文本中的特定单词(关键字)进行着色

问对<td>中的文本中的特定单词(关键字)进行着色
EN

Stack Overflow用户
提问于 2017-02-10 00:20:27
回答 2查看 406关注 0票数 0

我在一个项目中工作,现在我需要做一些我不知道的事情。我想给<td>内的文本中的特定单词(关键字)上色

我可以做静态,因为文本是随机的,它们来自数据库。

这是一个普通的文本,我想给像“动物,宠物”这样的单词上色。并为每个字体设置特定的颜色,例如,动物爱好者喜欢红色,宠物喜欢蓝色字体颜色。

我想我必须使用Jquery来处理它,并在页面加载后创建一个函数来完成它(readyFunction)。

但是我没有任何想法去做,我对jquery是新手。你能给我一些建议吗?

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-10 01:18:43

这确实是一个“肮脏”的解决方案,但它将作为如何处理任务的示例:

代码语言:javascript
复制
<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>
票数 0
EN

Stack Overflow用户

发布于 2017-02-10 02:05:56

假设您的浏览器支持html5,不需要JQuery,请尝试以下代码:

代码语言:javascript
复制
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>';
      },
      ''
    );      
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42141760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档