0

重複の可能性:
正規表現と JavaScript を使用して html 内の単語を強調表示する - ほとんどありません

更新 --> 解決された最終的なスクリプトは次のとおりです。

var regex;
var filterSize;

function normalizar(str) {
    var fin=str.toLowerCase().replace('á','a').replace('é','e').replace('í','i').replace('ó','o').replace('ú','u');

    return fin;
}

function highlight(fin) {
    htmlFin="";
    while ((match = regex.exec(normalizar(fin))) != null) {
        posIni=match.index;
        posEnd = posIni+filterSize;
        var ini="";
        if (posIni != 0) ini=fin.substring(0, posIni);
        var sub=fin.substring(posIni, posEnd);
        fin=fin.substring(posEnd, fin.length);

        htmlFin += ini+"<span class='highlight'>"+sub+"</span>";
    }
    htmlFin += fin;

    return htmlFin;
}

function procesar(elemento) {
    elemento.children().each(function() {
        var mas=$(this).children().size();
        if (mas == 0) {
            $(this).html(highlight($(this).text()));
        } else {
            procesar($(this));
        }
    });
}

$(document).ready(function(){

    $(".filter").keyup(function(){

        // Cogemos el texto de búsqueda
        var filter = $(this).val();
        //Ponemos el contador a 0
        var count = 0;
        $('span.highlight').each(function() {
            $(this).replaceWith($(this).text());
        });

        //Por cada elemento de la lista...
        $(".list tr:not(:first-child)").each(function(){
            var html=$(this).html();
            var posIni = -1;
            var posEnd = -1;

            filterNorm=normalizar(filter);
            filterSize=filter.length;
            regex=new RegExp(filterNorm, 'gi');
            var buscar=normalizar($(this).text()).search(regex);
            var htmlFin="";
            if (buscar > -1) {
                if (filter) procesar($(this));
                $(this).show();
                count++;

            } else $(this).fadeOut();
        });

        // Actualizamos la cuenta
        if (filter) {
            var numberItems = count;
            //Si no hay coincidencias lo mostramos en rojo.
            if (count==0) $(".cuenta").html("<span class='error'>Coincidencias = "+count+"</span>");
            else $(".cuenta").text("Coincidencias: "+count);
            //Si no hay filtro, limpiamos el html de cuentas.
        } else $(".cuenta").text("");
    });
});

入力内の一致を強調表示する jquery/javascript を使用して検索スクリプトを作成することが目標です。大文字と小文字の区別記号 (アクセント) 記号と html タグを無視する必要があります。

私はそれを行うのにとても近いですが、htmlタグを無視しないため失敗します。つまり、スクリプトのハイライトhtmlタグも一致します...

例えば:

更新: jsfiddle.net/josecash/nD6dg/2 でスクリプトを試すことができます 。tdまたは < または > と入力してエラーを確認してください。

次のようなテーブルがあるとしましょう。

<table>
<tr><th>Name</th><th>Kind</th><th>Type</th></tr>
<tr>
<td><strong>Fedora</strong></td>
<td>Linux</td>
<td>Operative System</td>
</tr>
</table>

入力に文字 o を入力すると、スクリプトはFedoraとオペレーティング システムのoだけでなく、タグ文字列のoも強調表示します。

正規表現変数の正規表現でそれができると思いますが、わかりません...

どんな助けでも本当に感謝します

スクリプトは次のようになります。

$(document).ready(function(){

    $(".filter").keyup(function(){

        // Input text
        var filter = $(this).val();
        //Ponemos el contador a 0
        var count = 0;
        $('span.highlight').each(function() {
            $(this).replaceWith($(this).text());
        });

        //Foreach tr in the table
        $(".list tr:not(:first-child)").each(function(){
            var html=$(this).html();
            var posIni = -1;
            var posEnd = -1;

                    // normalizar just replace accents
            filterNorm=normalizar(filter);
            var filterSize=filter.length;
            var regex=new RegExp(filterNorm, 'gi');
            var buscar=normalizar($(this).text()).search(regex);
            var htmlFin="";

            if (buscar > -1) {
                if (filter) {
                    var end=html;
                    while ((match = regex.exec(normalizar(end))) != null) {
                        posIni=match.index;
                        posEnd = posIni+filterSize;
                        var ini="";
                        if (posIni != 0) ini=end.substring(0, posIni);

                        var sub=end.substring(posIni, posEnd);
                        end=end.substring(posEnd, end.length);

                        htmlFin += ini+"<span class='highlight'>"+sub+"</span>";
                    }
                    htmlFin += end;
                }
                if (filter) $(this).show().html(htmlFin);
                else $(this).show();
                count++;
            } else $(this).fadeOut();
        });
    });
});
4

2 に答える 2

2

@ジョセカシュ、

HTML マークアップ自体の処理を避ける良い方法は、次のとおりです。

  • jQuery ではなくプレーンな JavaScript で子ノードを検出する
  • 遭遇したときにテキストノードを扱う
  • 要素ノードに遭遇すると (再帰的に) さらに侵入します。

全体的なコードは次のようになります。

$(document).ready(function(){
    //Highlighter function
    function highlight(text) {
        //Your highlight code here
        //...
        //return text with added HTML markup
    }

    //Recursive scanner function to penetrate the DOM tree.
    function scanNode(index, node) {
        //node is a plain javascript reference to a DOM node, not jQuery-wrapped.
        if(node.nodeType == 3) {//hurray, it's a TEXT_NODE
            $(node).replaceWith(highlight(node.nodeValue));
        }
        else if(node.nodeType == 1){//it's an ELEMENT_NODE
            //Here, for convenience, we use jQuery's utility `.each() method
            //but we are still essentially working in plain javascript.
            $.each(node.childNodes, scanNode);
        }
    }

    var $list = $(".list");
    //master routine
    $(".filter").keyup(function() {
        $list.find('span.highlight').each(function() {
            var $this = $(this);
            $this.replaceWith($this.text());
        }).find("tr:gt(1)").each(scanNode);
    });
});

以下の入力について@Bergiに感謝します

関数を作成する必要がありhighlight()ます。これは、上で提示したコードのかなり軽い変更になります。関数がマークアップされたテキスト文字列を返すことを確認してください。

重要な行$(node).replaceWith(highlight(node.nodeValue));はテスト済みです (Opera 12.12 および IE9 で)。jsフィドル

他のすべてはテストされていないため、デバッグが必要になる場合があります。

于 2013-01-13T20:48:14.337 に答える
0

'html' を正規表現テスト文字列として使用しないでください。代わりに、結果のテキストを使用してください。次のコードをテストします。

if (filter) {
      //replace this line:: var end=html;  by
      var end= $(this).text();
    ....
}
于 2013-01-13T16:25:17.580 に答える