wingmeng / front-end-quiz

前端小测试答题收集
0 stars 0 forks source link

DOM基础测试29:closest 和 closestAll 方法的实现 #6

Open wingmeng opened 5 years ago

wingmeng commented 5 years ago

题目:

image


我的答案:

我的回答:用 jQuery 的 closest() 方法。开个玩笑 :laughing:

先说下思路:根据传入的参数,使用 querySelectorAll() 方法找出所有匹配的选择器,再匹配出包含当前元素的 nodeList 列表。

第二题

第一题依赖这个方法,所以它先上


Element.prototype.closestAll = function(targetEl) {
var el = this;
var nodelist;

// 参数校验 if (typeof targetEl !== 'string' || !targetEl.trim()) { throw Error('\' + targetEl + \' is not a valid selector'); }

nodelist = document.querySelectorAll(targetEl);

// 使用 ES5 的 filter 过滤出包含 el 的元素 return [].slice.call(nodelist) .filter(function(node) { return node.contains(el) }) .reverse(); // 反转数组,最近的排前面,依次从近到远 }


#### 第一题
> 获取 `closestAll()` 方法返回的第一项即可
``` js
// closest polyfill
window.Element && 'closest' in Element.prototype || +function() {
  Element.prototype.closest = function(targetEl) {
    var result = this.closestAll(targetEl);
    return result.length === 0 ? null : result[0];
  }
}();
wingmeng commented 5 years ago

自我评分:优秀

优秀、良好、一般、差劲

学习收获:

  1. js 原生的 closest 方法