jquery重复节点匹配和删除

jquery duplicate nodes matching and removing

本文关键字:删除 节点 jquery      更新时间:2023-09-26

我有两个节点集,它们具有以下内容;

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也不会产生任何结果,还有其他有效的方法来完成我想要解决的问题吗?

不确定这是否符合要求,但变量对我来说就像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

FIDDLE作为要调用的函数(看起来更简单)!

应该补充一下,这对这样的东西不起作用

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

因为这些字符串不是逐字匹配的,尽管第二个字符串是第一个字符串的一部分等等,但在这种情况下,要删除字符串的类似部分,你总是可以这样做:

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, ''));

FIDDLE

快速浏览一下。也许这会有所帮助。它将在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/

您可以执行类似的操作

var obj1Txt= $(obj1).text();
var obj2txt= $(obj2).text();
var output= '<p>'+obj1txt.replace(obj2txt,'')+'</p>';

您可以尝试使用$.html()匹配字符串表示

return obj1.clone().html(obj1.html().replace(obj2.html(), ''))