递归:函数捕获我想要的元素但是没有返回它

时间:2018-03-12 14:21:01

标签: javascript recursion undefined

我有这个简单的函数来捕获特定的DOM元素:

_retrieveMainContactsBox(el){
    if(el.classList.contains('contacts')){
      return el
    }
    this._retrieveMainContactsBox(el.parentElement)
  }

但是当我在另一个函数中调用它时,它会返回undefined:

_initPhone(){
    let self = this;
    this.phoneTrigger.addEventListener('click',function(){
      if (window.matchMedia("(max-width: 893px)").matches){
        let main = self._retrieveMainContactsBox(this)
        console.log(main) // undefined
        TweenLite.to(main,.1,{width:"80%"})
      }
      TweenLite.to(self.phone,1,{autoAlpha:1,top:'0',left:'0',zIndex:20})

      $(self.phoneText).textillate('start')
    })
  }

基本上,主要变量的结果是未定义的,但是如果我在第一个函数中执行console.log,我想要的元素被打印出来,我不明白为什么不返回它。

1 个答案:

答案 0 :(得分:4)

  

我不会忘记为什么不归还

您还需要return递归调用,否则除非el classList具有该类,否则您可能会获得undefined从函数返回。

_retrieveMainContactsBox(el){
    if(el.classList.contains('contacts')){
      return el
    }
    return self._retrieveMainContactsBox(el.parentElement) //observe return here
}