【发布时间】:2021-05-21 03:20:47
【问题描述】:
好吧,所以我觉得我错过了一些东西,让我向您展示我编写的一个非常简单的函数。
function findClosestAncestor(html_child_element, html_class_name) {
if (!html_child_element.parentElement.classList.contains(html_class_name)) {
findClosestAncestor(html_child_element.parentElement, html_class_name)
} else {
return html_child_element.parentElement;
}
}
当我从我的页面中输入一个子元素时,我会调试这个函数,并且正如预期的那样,它在运行两次后会命中 else 语句。这已通过 Chrome 的开发工具对其进行实时调试得到确认,并且是我希望返回的页面上的元素。但是,当函数被调用并设置为这样的变量时
let parentPanel = findClosestAncestor(e.target, "panel");
parentPanel 在我退出函数后未定义。这让我有点困惑,我可能只是在这里忽略了一些非常简单的事情。发生了什么。
编辑: 根据 Thomas 的建议,我已经测试了 .closest() 这仍然没有返回值。 HTML结构的相关部分如下
<div class="list-info">
<div class="container">
<div class="account-type text-title">Type</div>
<div class="account-type-placeholder text-info">Type Placeholder</div>
</div>
<div class="container">
<div class="account-phone text-title">Phone</div>
<div class="account-phone-placeholder text-info">Phone Placeholder</div>
</div>
<hr /> <hr />
<button class="sublist-accordion">
<div class="sublist-title">
Other cases for this Customer
</div>
</button>
<div class="sublist-panel">
我们调用任一方法的元素是您在顶部看到的最终子列表面板。它应该是并且在我的方法成功找到上面的面板类的情况下。但是,它仍然不允许我将其分配为返回值,并且为我的方法和 .closest 都返回 undefined
【问题讨论】:
-
您可能想在您的
if块中添加return -
let parentPanel = e.target.closest(".panel");MDN Element#closest() -
@Thomas 我无权访问 jquery。
-
@Iptay 这是纯 JS,而不是 jquery。这就是我链接该方法的文档的原因。
-
@Iptay 鉴于您的调试器显示它命中了 else 语句,它是否还显示了 findClosestAncestor 的哪个迭代命中它?如果它是在前一次迭代的 if 部分中没有返回语句的二次迭代,则无法将结果通过调用堆栈传递给原始调用者。 (我会想到)。
标签: javascript