近距离方法总是返回“未定义”



我很难编写一个函数(或更具体的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函数的不同实现,并发现了一个使用进行循环的工作功能。但是除此之外,它是使用非常相似的方法。

这使我得出的结论是,我在递归中做错了什么。我只是看不到什么...有什么想法吗?

再次调用时,您没有返回它。这样更改它:

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
}

您需要从再次调用递归函数的点返回

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 
    }
    return this.findParent(element.parentNode) 
}

最新更新