【问题标题】:Highlight search text with jquery [duplicate]用jquery突出显示搜索文本[重复]
【发布时间】:2017-09-03 09:21:24
【问题描述】:

我正在尝试实现表格搜索,我在网上找到了答案并试了一下,效果很好!

现在我想突出显示 (change text colour: text color class= blue-text) 在表格单元格中找到的搜索关键字,我搜索了这个答案,但没有找到任何有用的信息!

我的 HTML 是

<table class="stdtable">
  <tr>
    <td id="stdname">Name</td>
    <td id="stdreg">Reg. No.</td>
    <td id="stdparent">Parent</td>
    <td id="stdgrp">Group</td>
    <td id="action">Action</td>
  </tr>
</table>

Jquery 是

$("#filter").on("keyup", function() {
    var searchKey = $(this).val().toLowerCase();
    $(".stdtable tr #stdname").each( function() {
        var searchStr = $(this).text().toLowerCase();
        if (searchStr.indexOf(searchKey)!=-1) {
            $(this).parent().show();
        }
        else {
            $(this).parent().hide();
        }
    });
});

如何突出显示搜索到的文本? 如果我搜索 NName 中的文本 N 应该会改变颜色

如果我清除搜索字段,我还需要清除文本的颜色

【问题讨论】:

标签: javascript jquery html search colors


【解决方案1】:

我不知道你的设置,但我会让一个类“突出显示” 并为此类提供属性:color: blue; 或您想要的任何其他 css 属性以获得特殊结果。 那么

$("#stdname").addClass("highlighted");

$("#stdname").removeClass("highlighted");

当您删除搜索字段时

编辑:将上面的内容留给想要所有文本的人。

你可以拿

var s = $(this).val();
var txt = $("#stdname").val().replace(s, '<span style="color: blue">' + s +  '</span>');
$("#stdname").val(txt);

请注意,如果每次按键启动时不从$("#stdname").val() 中删除 span 语句,您最终会出现奇怪的行为

【讨论】:

  • 不适用于整个字符串!只有我正在搜索的那些文本
  • 我修好了。尝试类似的东西,它应该能够改变颜色。为了清除,您必须删除 span 语句并将其替换为 "&gt;&lt;/span&gt;" 跨度之间的字符串。
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 2023-04-08
相关资源
最近更新 更多