11

我已经开始使用jQuery (v1.4.2) 的DataTables插件 (v1.6.2) ,我想问你是否知道允许我突出显示过滤行上搜索文本框中使用的文本的设置插件.

先感谢您

4

6 回答 6

15

我不得不建议突出显示插件:)

我现在在大约相同的情况下使用它,到目前为止它没有给我任何问题。

用法很简单:

$("#myTable").highlight($("#searchBox").val());

只需将突出显示的 CSS 类放在您想要的样式表样式中,就是这样:

.highlight { background-color: yellow }
于 2010-04-15T12:03:41.787 回答
6

我知道这个问题现在已经超过 6 年了,这里的答案可能会在你提问时对你有所帮助。但是对于仍在寻找这个的人来说,有一个新插件可以将mark.js(一个 JavaScript 关键字荧光笔)集成到 DataTables 中:datatables.mark.js

用法很简单:

$("table").DataTables({
    mark: true
});

这是一个例子:https ://jsfiddle.net/julmot/buh9h2r8/

这是最干净的方式,并且还为您提供了任何给定解决方案都没有为您提供的选项。

现在有一个官方的 DataTables博客文章可用。

于 2016-07-11T09:56:45.270 回答
5

您可以通过处理此内容来使用此功能:

jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
    oSettings.oPreviousSearch.oSearchCaches = {};       
    oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
    // Initialize search string array
    var searchStrings = [];
    var oApi = this.oApi;
    var cache = oSettings.oPreviousSearch.oSearchCaches;
    // Global search string
    // If there is a global search string, add it to the search string array
    if (oSettings.oPreviousSearch.sSearch) {
        searchStrings.push(oSettings.oPreviousSearch.sSearch);
    }
    // Individual column search option object
    // If there are individual column search strings, add them to the search string array
    if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
        for (var i in oSettings.aoPreSearchCols) {
            if (oSettings.aoPreSearchCols[i].sSearch) {
            searchStrings.push(oSettings.aoPreSearchCols[i].sSearch);
            }
        }
    }
    // Create the regex built from one or more search string and cache as necessary
    if (searchStrings.length > 0) {
        var sSregex = searchStrings.join("|");
        if (!cache[sSregex]) {
            var regRules = "("
            ,   regRulesSplit = sSregex.split(' ');

            regRules += "("+ sSregex +")";
            for(var i=0; i<regRulesSplit.length; i++) {
              regRules += "|("+ regRulesSplit[i] +")";
            }
            regRules += ")";

            // This regex will avoid in HTML matches
            cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
        }
        var regex = cache[sSregex];
    }
    // Loop through the rows/fields for matches
    jQuery('td', nRow).each( function(i) {
        // Take into account that ColVis may be in use
        var j = oApi._fnVisibleToColumnIndex( oSettings,i);
        // Only try to highlight if the cell is not empty or null
        if (aData[j]) {         
            // If there is a search string try to match
            if ((typeof sSregex !== 'undefined') && (sSregex)) {
                this.innerHTML = aData[j].replace( regex, function(matched) {
                    return "<span class='filterMatches'>"+matched+"</span>";
                });
            }
            // Otherwise reset to a clean string
            else {
                this.innerHTML = aData[j];
            }
        }
    });
    return nRow;
}, 'row-highlight');
return this;
};

里面 :

dataTables.search-highlight.js

像这个例子一样调用它:

<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.search-highlight.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
       var oTable = $('#example').dataTable();
       oTable.fnSearchHighlighting();
    } );
</script>

并将此代码添加到您的 css 文件中:

.filterMatches{
    background-color: #BFFF00;
}
于 2013-07-08T12:29:23.750 回答
0
<link href="https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.js"></script>

$("#tableId").dataTable({
    mark: true
});
于 2021-10-22T13:31:24.253 回答
-1

您可以使用以下插件

jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
    // Initialize regex cache
    oSettings.oPreviousSearch.oSearchCaches = {};

    oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        // Initialize search string array
        var searchStrings = [];
        var oApi = this.oApi;
        var cache = oSettings.oPreviousSearch.oSearchCaches;
        // Global search string
        // If there is a global search string, add it to the search string array
        if (oSettings.oPreviousSearch.sSearch) {
            searchStrings.push(oSettings.oPreviousSearch.sSearch);
        }
        // Individual column search option object
        // If there are individual column search strings, add them to the search string array

     //   searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
        var searchTxt = $('input[type="search"]').val();
        // console.log("txt" + searchTxt);
        if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
            for (var i in oSettings.aoPreSearchCols) {
                if (oSettings.aoPreSearchCols[i].sSearch) {
                searchStrings.push(searchTxt);
                }
            }
        }
        // Create the regex built from one or more search string and cache as necessary
        /*if (searchStrings.length > 0) {
            var sSregex = searchStrings.join("|");
            if (!cache[sSregex]) {
                // This regex will avoid in HTML matches
                cache[sSregex] = new RegExp("("+escapeRegExpSpecialChars(sSregex)+")(?!([^<]+)?>)", 'i');
            }
            var regex = cache[sSregex];
        }*/
        if (searchStrings.length > 0) {
            var sSregex = searchStrings.join("|");
            if (!cache[sSregex]) {
                var regRules = "("
                ,   regRulesSplit = sSregex.split(' ');

                regRules += "("+ sSregex +")";
                for(var i=0; i<regRulesSplit.length; i++) {
                  regRules += "|("+ regRulesSplit[i] +")";
                }
                regRules += ")";

                // This regex will avoid in HTML matches
                cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
            }
            var regex = cache[sSregex];
        }

        // Loop through the rows/fields for matches
        jQuery('td', nRow).each( function(i) {

            // Take into account that ColVis may be in use
            var j = oApi._fnVisibleToColumnIndex( oSettings,i);
            // Only try to highlight if the cell is not empty or null
         //   console.log("data "+ aData[j] + " j " + j);
         //   console.log("data 1  "+ nRow);
            if (aData) {
                // If there is a search string try to match
                if ((typeof sSregex !== 'undefined') && (sSregex)) {
                    //console.log("here :: "+$(this).text());
                    this.innerHTML = $(this).text().replace( regex, function(matched) {

                        return "<span class='filterMatches'>"+matched+"</span>";
                    });
                }
                // Otherwise reset to a clean string
                else {
                    this.innerHTML = $(this).text();//aData[j];
                }
            }
        });
        return nRow;
    }, 'row-highlight');
    return this;
};

这个解决方案对我有用。注意:目前它不支持单列过滤,但您只需在代码中取消注释以下内容。

searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");

我已经用数据表 1.10.2 和 jquery 1.9.2 版本对此进行了测试。

于 2014-10-02T15:01:37.580 回答
-2

此附加组件具有更好的突出显示搜索文本的功能。如果您在对话框中创建了数据表,则在对话框重新打开时您需要重新初始化数据表。

在 DatatableHighlighter.js 中

jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
    // Initialize regex cache
    oSettings.oPreviousSearch.oSearchCaches = {};

    oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        // Initialize search string array
        var searchStrings = [];
        var oApi = this.oApi;
        var cache = oSettings.oPreviousSearch.oSearchCaches;
        // Global search string
        // If there is a global search string, add it to the search string array
        if (oSettings.oPreviousSearch.sSearch) {
            searchStrings.push(oSettings.oPreviousSearch.sSearch);
        }
        // Individual column search option object
        // If there are individual column search strings, add them to the search string array

     //   searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
        var searchTxt = $('input[type="search"]').val();
        // console.log("txt" + searchTxt);
        if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
            for (var i in oSettings.aoPreSearchCols) {
                if (oSettings.aoPreSearchCols[i].sSearch) {
                searchStrings.push(searchTxt);
                }
            }
        }
        // Create the regex built from one or more search string and cache as necessary

        if (searchStrings.length > 0) {
            var sSregex = searchStrings.join("|");
            if (!cache[sSregex]) {
                var regRules = "("
                ,   regRulesSplit = sSregex.split(' ');

                regRules += "("+ sSregex +")";
                for(var i=0; i<regRulesSplit.length; i++) {
                  regRules += "|("+ regRulesSplit[i] +")";
                }
                regRules += ")";

                // This regex will avoid in HTML matches
                cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
                //cache[sSregex] = new RegExp(regRules+"", 'ig');
            }
            var regex = cache[sSregex];
        }

        // Loop through the rows/fields for matches
        jQuery('td', nRow).each( function(i) {

            // Take into account that ColVis may be in use
            var j = oApi._fnVisibleToColumnIndex( oSettings,i);

            if (aData) {
                // If there is a search string try to match
                if ((typeof sSregex !== 'undefined') && (sSregex)) {
                    //For removing previous added <span class='filterMatches'>
                    var element = $(this);//convert string to JQuery element
                    element.find("span").each(function(index) {
                        var text = $(this).text();//get span content
                        $(this).replaceWith(text);//replace all span with just content
                    }).remove();
                    var newString = element.html();//get back new string

                    this.innerHTML = newString.replace( regex, function(matched) {

                        return "<span class='filterMatches'>"+matched+"</span>";
                    });
                }
                // Otherwise reset to a clean string
                else {
                    //For removing previous added <span class='filterMatches'>
                    var element = $(this);//convert string to JQuery element
                    element.find("span").each(function(index) {
                        var text = $(this).text();//get span content
                        $(this).replaceWith(text);//replace all span with just content
                    }).remove();
                    var newString = element.html();
                    this.innerHTML = newString;//$(this).html()//$(this).text();
                }
            }
        });
        return nRow;
    }, 'row-highlight');
    return this;
};

并这样称呼它....

$("#button").click(function() {
                  dTable = $('#infoTable').dataTable({"bPaginate": false,"bInfo" : false,"bFilter": true,"bSort":false, "autoWidth": false,"destroy": true,
              "columnDefs": [
                               { "width": "35%", "targets": 0 },
                               { "width": "65%", "targets": 1 }
                             ]});
          $(".dataTables_filter input[type='search']").val('');
          $("span[class='filterMatches']").contents().unwrap();
          dTable.fnSearchHighlighting();
          $("span[class='filterMatches']").contents().unwrap();


        $("#AboutDialog").dialog('open');

    });
于 2016-01-13T11:00:38.947 回答