简体   繁体   English

我的递归函数没有返回任何东西

[英]My recursive function isn't returning anything

I'm trying to select a the parent form element of an input. 我正在尝试选择输入的父表单元素。 The form element isn't necessarily the direct parent node. 表单元素不一定是直接父节点。 Currently this outputs "undefined" to my log. 当前,这会向我的日志输出“未定义”。

var anInputElement = document.querySelector(...);
var formElement = getFormElement(anInputElement);
console.log(formElement);

function getFormElement(elem) {
  //if we've traversed as high as the `body` node then
  //we aint finding the `form` node
  if(elem.nodeName.toLowerCase() !== 'body') {
    var parent = elem.parentNode;
    if(parent.nodeName.toLowerCase() === 'form') {
      return parent;
    } else {
      getFormElement(parent);
    }
  } else {
    return false;
  }
}

Why am I getting undefined in my console log? 为什么在控制台日志中无法定义?

not just 不只是

getFormElement(parent);

but

return getFormElement(parent);

and simplified, just for fun: 和简化,只是为了好玩:

function getFormElement(elem) {
  if(elem.nodeName.toLowerCase() !== 'body') {
    var parent = elem.parentNode;
    return parent.nodeName.toLowerCase() === 'form' ? parent : getFormElement(parent);
  }

  return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的递归函数不返回最终结果? - Why isn't my recursive function returning the final result? 我的API调用什么都没有返回? - My API Call Isn't Returning Anything? 我的功能没有回来 - My function isn't returning 我的AJAX通话未返回任何内容,但也未失败 - My AJAX call is not returning anything but isn't failing either React JS:ForEach Function 没有返回任何东西 - React JS: ForEach Function isn't returning anything 我不知道为什么我的JavaScript函数Flip()不返回任何东西。 我希望它返回是正面还是反面 - I don't know why my function Flip() in JavaScript isn't returning anything. I want it to return if it is heads or tails 与这个过滤器函数相比有什么问题吗,因为它根本不返回任何东西 - Is anything wrong comparing with this filter function cause it isn't returning anything at all 为什么我的JavaScript倒数功能没有做任何事情? - Why isn't my JavaScript countdown function doing anything? Ajax 调用没有返回任何内容 - Ajax call isn't returning anything 具有externalheight函数的javascript选择器未返回任何内容,而且我也无法在其他任何地方选择选择器 - javascript selector with outerheight function isn't returning anything, and I can't select the selector anywhere else either
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM