[英]JavaScript Recursive Node Equivalence Function Not Working
我正在Chrome開發工具中測試以下代碼,即使兩個節點不相等,它也會一直返回true。 示例節點如下。 只有Div1和Div4相等。 我非常有信心我會遞歸地接觸所有節點,但是我認為我沒有使用'if'正確設置變量,或者我可能需要在其他地方放置-有點迷失了,嘗試了很多方法。
var htmlStrings = [
'<div id="one">Some<span>node <em>contents</em> for</span>comparison</div>',
'<div id="two">Some<span>node contents for</span>comparison</div>',
'<div id="one">Some<span>node <strong>contents</strong> for</span>comparison</div>',
'<div id="four">Some<span>node <em>contents</em> for</span>comparison</div>'
];
var div1 = document.createElement('div');
div1.innerHTML = htmlStrings[0];
document.body.appendChild(div1);
var div2 = document.createElement('div');
div2.innerHTML = htmlStrings[1];
document.body.appendChild(div2);
var div3 = document.createElement('div');
div3.innerHTML = htmlStrings[2];
document.body.appendChild(div3);
var div4 = document.createElement('div');
div4.innerHTML = htmlStrings[3];
document.body.appendChild(div4);
function nodeEquivalence(node1, node2) {
var passed = false;
if (node1.nodeType === node2.nodeType) {
if ((node1.tagName === node2.tagName || node1.nodeValue === node2.nodeValue)) {
passed = true;
}
}
node1 = node1.firstChild;
node2 = node2.firstChild;
while (node1 && node2) {
nodeEquivalence(node1, node2);
node1 = node1.nextSibling;
node2 = node2.nextSibling;
}
return passed;
}
console.log(nodeEquivalence(div1, div2));
console.log(nodeEquivalence(div1, div4));
這是一個適用於您的測試用例的實現。 這使用遞歸來測試子樹。 它專門編碼為處理元素,文檔,文檔片段,文本節點和注釋節點。 可以添加對其他類型節點的支持。
function nodeEquivalence(node1, node2) {
var ch1, ch2, nType;
// OK to have both node1 and node2 not exist, but only if both are missing
if (!node1 || !node2) {
return node1 === node2;
}
// must be same nodeType
ntype = node1.nodeType;
if (ntype !== node2.nodeType) {
return false;
}
// if there is a tagName, must be same tagName
if (node1.tagName && node1.tagName !== node2.tagName) {
return false;
}
switch(ntype) {
// nodes that have children
case 1: // element node
case 9: // document node
case 11: // document fragment node
// check equivalence on each corresponding child
ch1 = node1.firstChild;
ch2 = node2.firstChild;
while (ch1 && ch2) {
if (!nodeEquivalence(ch1, ch2)) {
return false;
}
ch1 = ch1.nextSibling;
ch2 = ch2.nextSibling;
}
return nodeEquivalence(ch1, ch2);
// nodes whose content is nodeValue
case 3: // text node
case 8: // comment node
return node1.nodeValue === node2.nodeValue;
// other types of nodes
default:
throw new Error("unsupported type of node");
break;
}
}
並且,一個有效的演示: http : //jsfiddle.net/jfriend00/nruL6fdy/
您的代碼邏輯存在許多問題:
if (node1.tagName === node2.tagName)
邏輯也會通過,因此您永遠不會比較nodeValue
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.