这是我的代码:
var findParentByClassName = function(element, targetClass) {
if (element) {
element.parentElement === null;
console.log("No parent found");
} if else {
element.parentElement !=== targetClass;
console.log("No parent found with that class name");
} else {
var currentParent = element.parentElement;
while (currentParent.className !== targetClass && currentParent.className !== null) {
currentParent = currentParent.parentElement;
}
return currentParent;
}
};
我需要能够检查其他两个条件:
- 检查所提供的“元素”是否有父元素。如果是,则将字符串发送到控制台。
- 如果找不到具有提供的“targetClass”名称的父级,则让它向控制台返回不同的字符串。
我假设这将通过 if - if-else - else 函数来完成,但对于我的一生,我只是无法得到它。
最佳答案
尝试使用这个(代码在代码片段下解释):
var findParentByClassName = function(elem, className)
{
if(elem == null)
{
console.log("No elem");
}
else if(elem.parentNode == null)
{
console.log("No parent");
}
else
{
console.log("Found a parent, looking for an ancestor with the given class name");
var ancestor = elem.parentNode;
while(ancestor != null)
{
if(ancestor.classList.contains(className))
{
console.log("Found ancestor with correct classname");
return parent;
}
}
}
console.log("Could not find parent with correct class name.");
return null;
};
首先,您仔细检查是否确实获得了一个元素。如果没有,我们无能为力。
然后,我们使用 else if
- 而不是 if else
- 来检查元素是否有父元素。如果没有,我们就无能为力了。
最后,如果我们有一个带有祖先的元素,我们的 else 分支就会被执行。从这一点开始,我们可以迭代地向上移动 DOM 树。如果我们找到一个其 classList 包含我们给出的 className 的元素,我们就找到了一个匹配的祖先,并返回它。否则,我们返回 null。
请注意,此代码查找具有匹配类名的祖先,该祖先不一定是直接父代。根据您的代码,我假设这就是您想要的。
现在,如果您使用 jQuery,这会变得更加容易:
var findParentByClassName = function(elem, className)
{
return $(elem).closest("." + className);
};
这里的缺点是您将无法记录解释的消息 为什么如果不存在具有正确类名的祖先,就找不到它。
以下是 if-else if-else 语句的工作原理:
if(condition)
{
// code to execute if the condition is true
}
else if(condition2) // condition2 is only checked if the 1st one is false
{
// code to run if condition2 is true
}
else if(condition3) // you can have 0 or more else if conditions
{
// in practice, you can have as many as you want
// there are limits, but you'll probably never reach them
// unless you're trying to
}
else
{
// code to execute if none of the conditions were true
}
条件是 bool 表达式。这些可以是 bool 值, 相等性检查,大于/小于,是否为变量 为空/未定义,依此类推。
我建议阅读 JavaScript 教程以获取更多信息。
关于javascript - 遍历 DOM 以确定父级的状态。根据条件返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42963970/