Open wingmeng opened 5 years ago
我的回答:用 jQuery 的 closest() 方法。开个玩笑 :laughing:
closest()
先说下思路:根据传入的参数,使用 querySelectorAll() 方法找出所有匹配的选择器,再匹配出包含当前元素的 nodeList 列表。
querySelectorAll()
第一题依赖这个方法,所以它先上 Element.prototype.closestAll = function(targetEl) { var el = this; var 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]; } }();
优秀
优秀、良好、一般、差劲
closest
题目:
我的答案:
我的回答:用 jQuery 的
closest()
方法。开个玩笑 :laughing:先说下思路:根据传入的参数,使用
querySelectorAll()
方法找出所有匹配的选择器,再匹配出包含当前元素的 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(); // 反转数组,最近的排前面,依次从近到远 }