我有一个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;
问题是它改变了所有下拉菜单的类,而不仅仅是单击了按钮的菜单。我可以执行任何操作,只会更改<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结构。
答案 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');
});
});
$('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;