我的jQuery“比较”函数有一些问题。其任务是比较两个文本区域并突出差异。比较两个客户端键入的文本字段jQuery
例如。 “我的名字是迈克尔”在一个文本区域,而“我的名字是米歇尔”在另一个文本区域。
我的函数将返回两个输入并突出显示第一个输入中的字符“a”,并突出显示第二个输入中缺少的字符。
这是功能看起来如何,但它似乎并没有100%的时间工作。
$(function() {
$('#btnCompare').on('click', function() {
compare();
});
function compare() {
$('#divColLeft').empty();
$('#divColRight').empty();
var textOne = $('#taOneComp').val();
var textTwo = $('#taTwoComp').val();
var output;
var outputX;
var arrTextOne = [];
var arrTextTwo = [];
for (var i = 0; i < textOne.length; i++) {
output = textOne.charAt(i);
arrTextOne.push(output);
}
for (var x = 0; x < textTwo.length; x++) {
outputX = textTwo.charAt(x);
arrTextTwo.push(outputX);
}
$.each(arrTextOne, function (y, e) {
if ($.inArray(e, arrTextTwo) == -1) {
$('#divColLeft').append(e);
$('#divColLeft').highlight(e);
} else {
$('#divColLeft').append(arrTextOne[y]);
}
});
$.each(arrTextTwo, function (z, f) {
if ($.inArray(f, arrTextOne) == -1) {
$('#divColRight').append(f);
$('#divColRight').highlight(f);
} else {
$('#divColRight').append(arrTextTwo[z]);
}
});
}
});
更新:为了更加精确,提高了原来的问题
如果某些模块主要包括炭“一”之前的任何两个文本的,这是应该强调的差异。在第一个文本中,应该突出显示“a”,在第二个文本中我想输入突出显示差异的空白空间(缺少的字符)。
您可能想要查看http://code.google.com/p/google-diff-match-patch/ – codelove
您认为该函数应该:“突出显示第二个字符中缺少的字符” 。你如何突出缺失的东西?你会插入一个空格字符在那个位置,然后突出显示? – Floremin
我过去几天看起来非常相似,并且发现[jsdiff](http://ejohn.org/projects/javascript-diff-algorithm/)对我来说非常合适。显示其工作的示例是[此链接](http://blog.djsipe.com/js-diff/)。 – Fergus