2

次の内容のノードセットが2つあります。

obj1 "<p>the quick <b>brown</b> fox jumped over the fence</p>"
obj2 "<p>the quick <b>brown</b> fox </p>"

obj1の内容をobj2と一致させてから、一致したノードを削除して、次のようなオブジェクトを残そうとしています。

output "<p>jumped over the fence</p>"

jquery $ .matchを使用するとエラーが返され、$。findでも結果が得られません。私が解決しようとしていることを実行する他の効果的な方法はありますか?

4

4 に答える 4

2

これが要件に適合するかどうかはわかりませんが、変数は私にはHTML文字列のように見えます。元のメイン要素を失うことなく、文字列を単語ごとに比較したいようです。次のようにします。

var obj1 = "<p>the quick <b>brown</b> fox jumped over the fence</p>",
    obj2 = "<p>the quick <b>brown</b> fox </p>";

var obj3 = compare(obj1, obj2);

$('body').append(obj3);


function compare(elm1, elm2) {
    var obj = [],
        o1 = String($(elm1).html()).split(' '), //get <p>'s inner HTML as string and split on spaces to get each word
        o2 = String($(elm2).html()).split(' ');

    $.each(o1, function(i,e) { //iterate over each word inside <p> of first string
        if (e !== o2[i]) obj.push(e); //check if matches each word in the same loaction in the second string
    });
    //we should now have an array of the words that does not match each other
    return $(elm1).clone().html(obj.join(' ')); //join with new spaces and return the string as html contained in a clone of the original element.
}

フィドル

呼び出す関数としてのFIDDLE (より単純なようです)!

これは次のようなものでは機能しないことを追加する必要があります:

var obj1 = "<p>the quick <b>brown</b> fox jumped over the fence</p>",
    obj2 = "<p>fox jumped over the fence</p>";

これらの文字列は単語の一致を表すものではないため、2番目は最初の文字列などの一部ですが、このようなイベントで文字列の同様の部分を削除するには、いつでも次のようにすることができます。

var obj1 = "<p>the quick <b>brown</b> fox jumped over the fence</p>",
    obj2 = "<p>fox jumped over the</p>",
    o1 = String($(obj1).html()),
    o2 = String($(obj2).html());

var obj = $(obj1).clone().html(o1.replace(o2, ''));

フィドル

于 2012-08-21T20:13:01.723 に答える
1

ちょっと刺すだけ。多分これは役に立ちます。HTMLに太字のタグが残り、直接の質問以外はカバーされない可能性があります。

var obj1 = "<p>the quick <b>brown</b> fox jumped over the fence</p>";
var obj2 = "<p>the quick <b>brown</b> fox </p>";

var result="";
var inTag=false;

for (i=0;i<obj1.length;i++)
{
    if(obj1[i]=='<')
        isTag=true;
    if(!isTag)
    {
        if(i<obj2.length-1)
        {
            if(obj1[i]!=obj2[i])
            {
                result+=obj1[i];
            }
        }
        else
        {
            result+=obj1[i];
        }
    }
    else
    {
        result+=obj1[i];
    }
    if(obj1[i]=='>')
        isTag=false;
}

$("#result").html(obj1+obj2 + "<p>Difference:</p>"+result);​

http://jsfiddle.net/8qYV4/1/

于 2012-08-21T20:11:27.077 に答える
0

あなたはこのようなことをすることができます

var obj1Txt= $(obj1).text();
var obj2txt= $(obj2).text();
var output= '<p>'+obj1txt.replace(obj2txt,'')+'</p>';
于 2012-08-21T20:12:08.640 に答える
-1

$ .html()を使用して、文字列表現の照合を試みることができます。

return obj1.clone().html(obj1.html().replace(obj2.html(), ''))
于 2012-08-21T20:06:48.587 に答える