Rplus / f2e-note

record some note in issue
0 stars 0 forks source link

about jQuery polyfill #21

Open Rplus opened 8 years ago

Rplus commented 8 years ago

$.fn.closest

https://api.jquery.com/closest/

選擇 parents 符合 selector 的 element

jQuery src: for 迴圈刷 parent() https://github.com/jquery/jquery/blob/3.0.0-alpha1/src/traversing.js#L63-L89


polyfill - 0 使用原生的 DOM4 mathod Element.closest() MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

IE, Safari GG


polyfill - 1: ref: http://stackoverflow.com/a/16430350/3893926

也是要跑遞迴的迴圈

function closest(elem, selector) {

   var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector;

    while (elem) {
        if (matchesSelector.call(elem, selector)) {
            return elem;
        } else {
            elem = elem.parentElement;
        }
    }
    return false;
}

polyfill - 2 ref: http://stackoverflow.com/a/26997490

function closest(el, sel) {
    if (el != null)
        return el.matches(sel) ? el 
            : (el.querySelector(sel) 
            || closest(el.parentNode, sel));
}

Element.prototype.matches = (Element.prototype.matches || Element.prototype.mozMatchesSelector 
    || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector 
    || Element.prototype.webkitMatchesSelector || Element.prototype.webkitMatchesSelector);

polyfill - 3 dom4.js: https://github.com/WebReflection/dom4/