简体   繁体   English

如果child aria-expanded = true,则将类添加到父元素

[英]If child aria-expanded=true add class to parent element

How can I add a class to a parent element if aria-expanded=true ? 如果aria-expanded=true如何将类添加到父元素?

I have the following markup: 我有以下标记:

 $(function () { if ($('.navbar-collapse').attr('aria-expanded') === "true") { $(this).parents("header").addClass('red'); } }); 
 .red { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <header class="navbar navbar-s" id="master" role="banner"> <div class="container"> <nav id="main-navbar" class="navbar-collapse" role="navigation" aria-expanded="true"> Navigation </nav> </div> </header> 

I think the if-query works but not the other code. 我认为if查询有效,但其他代码无效。

The issue you have is that this within the if condition will refer to the window , not your selected .navbar-collapse element. 你的问题是, this范围内的if条件将参照window ,而不是你选择.navbar-collapse元素。

To solve this you could use the 'attribute selector' to retrieve the element then chain the required methods calls to add the class to the parent target Try this: 为了解决这个问题,您可以使用“属性选择器”来检索元素,然后链接所需的方法调用以将该类添加到父目标中,请尝试以下操作:

 $(function() { $('.navbar-collapse[aria-expanded="true"]').closest('header').addClass('red'); }); 
 .red { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <header class="navbar navbar-s" id="master" role="banner"> <div class="container"> <nav id="main-navbar" class="navbar-collapse" role="navigation" aria-expanded="true"> Navigation </nav> </div> </header> 

this in if block doesn't refers to the nav element thus your didn't work. if块中的this并不指向nav元素,因此您没有工作。

You can use Attribute Equals Selector [name=”value”] to target element then traverse up. 您可以使用“ Attribute Equals Selector [name=”value”]来定位元素,然后向上移动。

 $(function() { $('.navbar-collapse[aria-expanded="true"]').parents("header").addClass('red'); }); 
 .red { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <header class="navbar navbar-s" id="master" role="banner"> <div class="container"> <nav id="main-navbar" class="navbar-collapse" role="navigation" aria-expanded="true"> Navigation </nav> </div> </header> 

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

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