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/ehzPQ/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 に答える