【发布时间】: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>
【问题讨论】:
标签: javascript jquery html jsp highlight