【问题标题】:how to auto highlight sentence in the content javascript html如何在内容javascript html中自动突出显示句子
【发布时间】:2016-11-04 15:35:59
【问题描述】:

https://jsfiddle.net/bob90937/2yw3s376/ 正如您从以下内容中看到的那样,我可以在一个内容中使用一个句子 jsp,html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<p id="sentence">a paragraph</p>
<p id="content">And this here is inside a paragraph , about paragliders. happy ending.</p>

css:

.highlighted {
  background: yellow
}

javascript:

$(document).ready(function() {

  var wordText = $('#sentence').text();
  var rootText = $('#content').text();
  var rootNode = document.getElementById('content');

  highlightWord(rootText, wordText);

  function highlightWord(rootText, wordText) {

    textNodesUnder(rootNode).forEach(highlightWords);

    function textNodesUnder(rootNode) {
      var walk = document.createTreeWalker(rootNode, NodeFilter.SHOW_TEXT, null, false);
      var text = [],
        node;
      while (node = walk.nextNode()) text.push(node);

      return text;
    }

    function highlightWords(n) {
      for (var i;
        (i = n.nodeValue.indexOf(wordText, i)) > -1; n = after) {
        var after = n.splitText(i + wordText.length);
        var highlighted = n.splitText(i);
        var span = document.createElement('span');
        span.className = 'highlighted';
        span.appendChild(highlighted);
        after.parentNode.insertBefore(span, after);
      }
    }
  }

});

如果我有多个句子和内容,我将其保存在表格中。 怎么改代码让多句多内容都能高亮显示???

..

  <table class="gridtable" border="1"> 
<tbody>
<tr>
    <th>sentence</th>
    <th>content</th>

  </tr>

<tr>
<td id="sentence">a paragraph</td>
<td id="content">And this here  is inside a paragraph , about paragliders.happy ending.</td> 
<tr>
<td id="sentence">unless they were granted</td>
<td id="content">All Singaporean children of school-going age are required to regularly attend a national primary school, unless they were granted an exemption due to physical or intellectual disabilities.</td> 
<tr>
<td id="sentence">efforts to</td>
<td id="content">MOE said that the change is part of the Government ongoing efforts to build a more inclusive society.</td> 
</tr>
</table> 

https://jsfiddle.net/bob90937/2yw3s376/链接

【问题讨论】:

  • 你为什么不用mark.js
  • 另外,请提供一个可以运行的示例代码,例如jsfiddle!您的代码包含模板内容,因此我们无法对其进行测试。
  • 嘿。你的句子是动态的还是静态的?
  • @Darence30 存储在数组中的句子。句子总是内容的一部分

标签: javascript jquery html jsp highlight


【解决方案1】:

您有身份冲突。您提供了 contentsentence 的多个元素 ID。您的 Javascript 仅检索它找到的第一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 2016-08-12
    • 2021-10-01
    • 2019-07-25
    • 2011-09-20
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多