jQuery on click事件不适用于切换类 [英] jQuery on click event not working on toggled class

查看:127
本文介绍了jQuery on click事件不适用于切换类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆