我有一个非常简单的设置:
但由于某种原因,这条线不起作用:
$('.toggled .has-children').on('click', function(e){
是否因为该类动态添加到父级?我怎么克服这个?
$(function() {
var container = $('.nav');
var button = $('.menu');
//add remove class to nav
button.on('click', function () {
if(container.hasClass('toggled')) {
container.removeClass('toggled');
} else {
container.addClass('toggled');
}
});
// doesn't work?
$('.toggled .has-children').on('click', function(e){
e.preventDefault();
$(this).attr('aria-expanded', 'true');
})
});
.toggled {
color: blue;
}
.has-children[aria-expanded=true] {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
<button class="menu">Menu</button>
<ul>
<li class="has-children" aria-expanded="false">
Has children
</li>
</ul>
</nav>
答案 0 :(得分:1)
这不起作用,因为在添加切换类之前绑定了click事件。
您只应在添加切换后绑定点击次数:
$(function() {
var container = $('.nav');
var button = $('.menu');
var addExpanded = function(){
$('.toggled .has-children').unbind().on('click', function(e){
e.preventDefault();
$(this).attr('aria-expanded', 'true');
})
}
//add remove class to nav
button.on('click', function () {
if(container.hasClass('toggled')) {
container.removeClass('toggled');
} else {
container.addClass('toggled');
addExpanded()
}
});
});
答案 1 :(得分:1)
如果能够基于 static 元素(例如body
)使点击侦听器成为动态侦听器就足够了:
$('body').on('click', '.toggled .has-children', function(e){
见下面的工作演示:
$(function() {
var container = $('.nav');
var button = $('.menu');
//add remove class to nav
button.on('click', function() {
if (container.hasClass('toggled')) {
container.removeClass('toggled');
} else {
container.addClass('toggled');
}
});
$('body').on('click', '.toggled .has-children', function(e) {
e.preventDefault();
$(this).attr('aria-expanded', 'true');
})
});
&#13;
.toggled {
color: blue;
}
.has-children[aria-expanded=true] {
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
<button class="menu">Menu</button>
<ul>
<li class="has-children" aria-expanded="false">
Has children
</li>
</ul>
</nav>
&#13;