繁体   English   中英

如何编写if / else语句以检查是否选择了子元素?

[英]How to write an if/else statement to check whether or nor a child element is selected?

想象一下,我有一个div,其中有几个后代/孩子:

<div class="currenTile" tabindex="0">
  <h1 tabindex="0"> my Header </h1>
  <p tabindex="0"> some text </p>
  <ul tabindex="0">
     <li tabindex="0"> item 1 </li>
     <li tabindex="0"> item 2 </li>
     <li tabindex="0"> item 3 </li>
  </ul>
</div>

我想创建一个“ if / else”语句,该语句在击键事件后检查某个元素是否具有焦点并且是“ currentTile” div的子元素,以执行某些操作。 关于如何执行此操作的任何想法?

这可能会达到目的:

$(document).on("keydown", function() {
    var isChildOfDiv = $(":focus").parents("div.currenTile").length > 0;
    console.log(isChildOfDiv); //true if element with focus is within the div, false otherwise
});

JSFiddlehttps : //jsfiddle.net/9rvyps8g/

$(":focus")获取具有焦点的当前元素,然后使用.parents()检查该元素的所有父元素,并将div的类传递给它。

请记住,这是按原样进行的,因为该类只有一个div。 我没有测试过同一个类的其他div会发生什么,尽管我认为不会发生任何事情。 如果只需要一个div,请改用ID。

您可以通过以下方法进行检查:

if($("#myElement").is(":focus") && $("#myElement").closest(".currenTile").length > 0)

#myElement是您要检查的任何元素。 is(“:focus”)检查其焦点是否明显且最接近()从该元素爬到DOM,以查找具有该类名称的父元素

给您的元素ID为“独角兽”或任何您想要的名称。

//Assuming you have keydown event check first

if (document.activeElement.parent().getAttribute("id") == "unicorn") {
//Do Stuff with document.activeElement
}
else {
//Do Different Stuff with document.activeElement
}

根据您的代码,可能会有更好的方法来识别父对象。

如果要检查所有后代:

//Assuming you have keydown event check first
var x = document.activeElement();
var found = false;
while (x=x.parentElement) {
    if (x.parent().getAttribute("id") == "unicorn") {
        found = true;
        break;
    }
}
if (found) {
     //Do Stuff with document.activeElement
}
else {
     //Do Different Stuff with document.activeElement
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM