jQuery on click事件不适用于切换类 [英] jQuery on click event not working on toggled class
问题描述
我在jQuery中尝试了"on","live"和"delegate"方法,但似乎无济于事.
我想要做的是当用户单击类为.signin
的登录按钮时,切换名为.menu-open
的类.然后,当我再次单击该按钮时,我想发出警报!
$(document).ready(function() {
$(".signin").click(function(e) {
e.preventDefault();
$(".signin").toggleClass("menu-open");
});
$('.menu-open').on('click', function() {
alert("SUCCESS");
});
});
这是因为在页面加载时,文档中没有类为.menu-open
的元素,因此查询无提示失败,您应该委派该事件.
$(document).on('click', '.menu-open', function() {
alert("SUCCESS");
});
请注意,使用静态父元素比使用document
对象作为委托目标更为有效.
I have tried "on","live", and "delegate" methods in jQuery, but nothing seems to work.
What i want to do is when user clicks on sign in button with a class of .signin
, to toggle a class named .menu-open
. and then, i want alert something when i click on that button again!
$(document).ready(function() {
$(".signin").click(function(e) {
e.preventDefault();
$(".signin").toggleClass("menu-open");
});
$('.menu-open').on('click', function() {
alert("SUCCESS");
});
});
That's because on the page load there is no element with class of .menu-open
in the document so the query silently fails, you should delegate the event.
$(document).on('click', '.menu-open', function() {
alert("SUCCESS");
});
Note that using a static parent element is more efficient than using document
object as the target of delegation.
这篇关于jQuery on click事件不适用于切换类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!