jQuery:只影响具有某个类的元素,这些元素是另一个元素的子元素

时间:2017-10-15 17:11:54

标签: javascript jquery dom

我有一个jQuery函数,通过点击更改其类来切换下拉导航菜单:



library(ggplot2)

df <- data.frame(recividism = sample(0:2, 100, replace = T),
                 TotalDays = sample(15:1000, 100, replace = T),
                 NumEnroll = sample(1:7, 100, replace = T))

df$recividism <- as.factor(df$recividism)

levels(df$recividism) <- c("Not Perm", "Perm", "Rec")

ggplot(data = df, aes(x = TotalDays)) + 
  geom_histogram(aes(fill = recividism), position = "fill" ) + 
  facet_grid(facets = NumEnroll ~ .)
&#13;
$(function () {
     $('.nav-titles').on('click', function() {
        $('.nav-dropdown').toggleClass('nav-dropped-down');
     });
});
&#13;
&#13;
&#13;

问题是它改变了所有下拉菜单的类,而不仅仅是单击了按钮的菜单。我可以执行任何操作,只会更改<nav> <li> <a class="nav-titles"></a> <div class="nav-dropdown"></div> </li> <li> <a class="nav-titles"></a> <div class="nav-dropdown"></div> </li> <li> <a class="nav-titles"></a> <div class="nav-dropdown"></div> </li> <li> <a class="nav-titles"></a> <div class="nav-dropdown"></div> </li> <li> <a class="nav-titles"></a> <div class="nav-dropdown"></div> </li> </nav>按钮下的.nav-dropdown吗?

根据要求添加了HTML结构。

2 个答案:

答案 0 :(得分:1)

您需要找到父li元素,并在其上查找下拉类:

$('.nav-titles').on('click', function() {
    $(this).closest('li').find('.nav-dropdown').toggleClass('nav-dropped-down');
});

答案 1 :(得分:0)

问题在于,您无法点击nav-titles课程,因为它已被li家长包裹,因此您必须为点击广告选择li标记。不是nav-titles类,而是在其中搜索nav-dropdown类。

$(function () {
     $('.nav-titles').on('click', function() {
        $(this).closest('.nav-dropdown').toggleClass('nav-dropped-down');
     });
});

&#13;
&#13;
$('li').on('click', function() {

      $(this).find('.nav-dropdown').toggleClass('nav-dropped-down');
});
&#13;
.nav-dropped-down
{
height:20px;
background-color:red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
	<li>
		<a class="nav-titles"></a>
		<div class="nav-dropdown"></div>
	</li>
	<li>
		<a class="nav-titles"></a>
		<div class="nav-dropdown"></div>
	</li>
	<li>
		<a class="nav-titles"></a>
		<div class="nav-dropdown"></div>
	</li>
	<li>
		<a class="nav-titles"></a>
		<div class="nav-dropdown"></div>
	</li>
	<li>
		<a class="nav-titles"></a>
		<div class="nav-dropdown"></div>
	</li>
</nav>
&#13;
&#13;
&#13;