0

我正在尝试使用 javascript 使用文本突出显示选项。我知道如何找到字符串的起始位置,但如何使它突出显示。我的代码看起来像

<div id="entity">health insurance</div>
<div id="article">This kind of insurance is meant to supplement health insurance for cancer-care costs. But generally you're better off putting your money toward comprehensive health policies. </div>

和我用过的javascript

$(document).ready(function()
{
var test=document.getElementById('article').innerHTML;
var variable=document.getElementById('entity').innerHTML;
alert(test.search(new RegExp(variable, "i")));
});

这将提醒字符串的起始位置。

4

2 回答 2

1

HTML:

<div id="entity">health insurance</div>
<div id="article">This kind of insurance is meant to supplement health insurance for cancer-care costs. But generally you're better off putting your money toward comprehensive health policies. </div>​

CSS:

.highlight {
  background-color: yellow
}

Javascript:

$(document).ready(function () {​
  var $test = $('#article');
  var entityText = $('#entity').html();
  var highlight = '<span class="highlight">' + entityText + '</span>';
  $test.html($test.html().replace(entityText, highlight));
}

演示:http: //jsfiddle.net/ezhPQ/2/

因此,我只是将第一次出现的“实体”字符串替换为包含在跨度类中的相同字符串。

我理解你的问题了吗?

- - - - - - - - - - - -更新 - - - - - - - - - - - - -

如果要突出显示所有出现的修改,请使用正则表达式:

更新的 Javascript:

$(document).ready(function () {
  var $test = $('#article');
  var entityText = $('#entity').html();
  var entityRegularExpression = new RegExp("\\b" + entityText + "\\b", "gi");
  var highlight = '<span class="highlight">' + entityText + '</span>';
  $test.html($test.html().replace(entityRegularExpression, highlight))
}

并更新了演示:http: //jsfiddle.net/ehzPQ/3/

于 2012-06-05T14:20:48.303 回答
0

只需替换yourDesireString<span class='highlight'>yourDesireString</span>.

span.highlight {
     background-color: yellow;
}
于 2012-06-05T14:01:26.967 回答