简体   繁体   English

在JavaScript中生成两个DOM元素(而不是两个字符串)的差异

[英]Generating a diff of two DOM elements (rather than two strings) in javascript

This works really well for strings: http://ejohn.org/projects/javascript-diff-algorithm/ 这对于字符串非常有效: http : //ejohn.org/projects/javascript-diff-algorithm/

And I used to do string diffing server side (in ruby), but It's really hard to also take into consideration forced tag structure, like in tables. 我曾经在服务器端(使用ruby)做字符串差异处理,但是要像表中那样考虑强制标记结构确实非常困难。

What I did with just non table html was too add spans around the added and deleted text / inline elements. 我对非表格html所做的操作也是在已添加和已删除的text / inline元素周围添加跨度。 That method works well until you start trying to diff groups of TDs. 在您开始尝试比较TD组之前,该方法效果很好。

So, is there any Javascript library out there that will generate a visual diff with tables? 那么,是否有任何Javascript库可以与表生成视觉差异?

UPDATE / Example: 更新/示例:

Table1:                    Table 2:

<table>                     <table>
    <tr>                        <tr>
        <td>sometext</td>           <td>some <b>text</b></td>
        <td>moretext</td>           <td><b>more text</b></td>
    </tr>                       <tr>
</table>                    </table>

Resulting Table (just a possibility, as there are many ways to show diffs) 结果表(这是一种可能性,因为有很多方法可以显示差异)

<table>
    <tr>
        <td>some<del>text</del><add> <b>text</b></add></td>
        <td><del>more text</del><add><b>more text</b></add></td>
    </tr>
</table>

Here is my initial attempt. 这是我最初的尝试。 It uses the diff library that you referenced and assumes that the tables are of the same dimensions. 它使用您引用的diff库,并假定表的尺寸相同。

$(document).ready(function() {
    $("#tbl1 tbody").children("tr").each(function(rownum, tr) {
        _tr = $("<tr>");
        tr2 = $($("#tbl2 tbody tr").get(rownum));
        $(tr).children("td").each(function(colnum, td) {
            text = $(td).html();
            text2 = $($(tr2).children("td").get(colnum)).html();
            _tr.append("<td>" + diffString(text, text2) + "</td>");
        });
        $("#results").append(_tr);
    });
});​

http://jsfiddle.net/SPSJb/ http://jsfiddle.net/SPSJb/

I recently implemented https://github.com/teamwork/visual-dom-diff which compares 2 DOM nodes and generates a DocumentFragment with all differences wrapped in <ins> and <del> elements as appropriate. 我最近实现了https://github.com/teamwork/visual-dom-diff ,它比较了2个DOM节点并生成了一个DocumentFragment其中所有差异都适当地包装在<ins><del>元素中。 It think it could be appropriate for your use case. 它认为这可能适合您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM