如何在结果中突出显示搜索到的字符串?

时间:2014-02-07 12:21:10

标签: javascript jquery html

我使用Like关键字提取数据,这意味着结果可能不完全匹配。现在我想突出显示整个数据的searched string形式?我在table中显示数据。 有没有简单的方法呢?

Here is code to show data

<table class="table table-striped table-bordered bootstrap-datatable datatable">
  <thead>
      <tr>
          <th>Surah</th>
          <th>Ayah</th>
          <th>Contents</th>
      </tr>
 </thead>   
  <tbody>    
    @foreach (var n in @ViewBag.test)
    {
        <tr>
        <td class="center"> @n.surah_name </td>
        <td class="center">    @n.ayah  </td>
        <td style="text-align:right; font-size: 20px; height:90px; vertical-align:middle; line-height : 75px"> @n.verse   </td>
       </tr>
    }

         </tbody></table>

我想在按钮的点击事件上突出显示!

1 个答案:

答案 0 :(得分:2)

// escape by Colin Snover
// Note: if you don't care for (), you can remove it..
RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

function highlight(term, base) {
  if (!term) return;
  base = base || document.body;
  var re = new RegExp("(" + RegExp.escape(term) + ")", "gi"); //... just use term
  var replacement = "<span class='highlight'>" + term + "</span>";
  $("*", base).contents().each( function(i, el) {
    if (el.nodeType === 3) {
      var data = el.data;
      if (data = data.replace(re, replacement)) {
        var wrapper = $("<span>").html(data);
        $(el).before(wrapper.contents()).remove();
      }
    }
  });
}

function dehighlight(term, base) {
  var text = document.createTextNode(term);
  $('span.highlight', base).each(function () {
    this.parentNode.replaceChild(text.cloneNode(false), this);
  });
}

<强> See it in action

来自:https://stackoverflow.com/a/3241437/3272179