Javascript jQuery插件数据表:如何突出显示当前搜索文本?

Javascript jQuery插件数据表:如何突出显示当前搜索文本?,javascript,jquery,datatables,Javascript,Jquery,Datatables,我已经开始为jQuery(v1.4.2)使用DataTables插件(v1.6.2),我想问您是否知道一个设置或一个插件,它允许我在过滤行上突出显示搜索文本框中使用的文本 提前谢谢我得建议:) 我现在在同样的场景中使用它,到目前为止,它没有给我任何问题 用法非常简单: $("#myTable").highlight($("#searchBox").val()); 只需将highlight CSS类放入样式表样式中即可: .highlight { background-color: yellow

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


提前谢谢

我得建议:)

我现在在同样的场景中使用它,到目前为止,它没有给我任何问题

用法非常简单:

$("#myTable").highlight($("#searchBox").val());
只需将highlight CSS类放入样式表样式中即可:

.highlight { background-color: yellow }

您可以通过以下方式使用此功能:

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;
};

您可以使用以下加载项

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;
};

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

此附加组件具有更好的突出显示搜索文本的功能。若您已经在对话框中创建了datatable,那个么在对话框重新打开时,您需要重新初始化datatable

在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;
};

我知道这个问题已经有6年多的历史了,这里的答案在提问时可能会对你有所帮助。但对于仍在搜索的人来说,有一个新的插件可以集成到DataTables中——一个JavaScript关键字highlighter:

用法非常简单,如下所示:

$("table").DataTables({
    mark: true
});
以下是一个例子:

这是最干净的方法,也为您提供了所有给定解决方案都无法提供的选项


现在有一个官方的DataTables可用。

是的,这是一个很棒的小插件,代码非常清晰,是如何实现这类功能的一个很好的例子。但是DataTables中默认没有id为searchBox的元素。你是如何添加它的?@iamrohitbanga-这只是你在页面上的一些
元素,可以触发此更改或键控,点击按钮…你想要的任何UI。更好的是:$table.on('search.dt',function(){$table.on('draw.dt',function(){var api=$table.api();$('tbody',$table)。突出显示(api.search这在新的API下工作:$table.on('search.dt',function(){$(This.dataTable().on('draw.dt',function(){var term=$(This.dataTable().API().search();$('tbody',This)。突出显示(term);});该代码有很多错误,因为它不能处理将json数据加载到datatable时的情况,无论是否进行服务器端处理。我确认这也是有效的方法。
searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
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');

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