我很难编写一个函数(或更具体的 ES6 类方法)来返回与指定选择器匹配的最接近父元素的元素。
我的函数再次递归调用自身,直到在当前元素 classList
属性中找到所需的类。
如果我记录元素,我会得到我想要的确切元素,但如果我记录函数调用本身,它总是返回 undefined
。
这是我的代码:
findParent (element, selector) {
if (element === document) return null // stops when at end of tree
if (element.classList.contains('foo-selector')) {
console.log(element) // logs the expected element
return element // returns 'undefined'
}
this.findParent(element.parentNode) // function calls itself again
}
我做了一些实验,查看了 getClosest 函数的不同实现,发现了一个使用 for 循环 的有效实现。但除此之外,它使用了非常相似的方法。
这让我得出结论,我在递归方面做错了什么;我只是看不到什么... 有什么想法吗?
最佳答案
当你再次调用它时,你不会返回它。像这样改变它:
findParent (element, selector) {
if (element === document) return null // stops when at end of tree
if (element.classList.contains('foo-selector')) {
console.log(element) // logs the expected element
return element // returns 'undefined'
}
return this.findParent(element.parentNode) // function calls itself again
}
关于javascript - closestParent 方法总是返回 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43677502/