Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

看了汤姆大叔的一篇博文后,有一个疑问

问题描述:

在最后一个`return`中,首先排除了自身`el === b`,又继而判断`el != b`,不理解为什么要这样做,难道会出现`el == b`的情况吗?
var contains = (function () {
    var docEl = document.documentElement;

    if (typeof docEl.compareDocumentPosition != 'undefind') {
        return function (el, b) {
        }
    } else if (typeof docEl.contains != 'undefind') {
        return function (el, b) {
            return el !== b && el.contains(b);
        }
    }
    return function (el, b) {
        if (el === b) return false;
        while (el != b && (b = b.parentNode) != null);  // 疑惑在这里
        return el === b;
    }
})()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
while (el != b && (b = b.parentNode) != null);

等效于

while(el != b)
{
     b = b.parentNode;
     if(b === null)
         break;
}

等效于

while(b !== null)
{
     if(el === b)
         break;
         
     b = b.parentNode;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...