日期:2014-05-16  浏览次数:20339 次

关于jquery的on方法在动态改变元素class之后
本帖最后由 chrislee1981 于 2013-05-29 12:16:10 编辑
代码如下
$('.a').on('click',function(){
  alert('a');
  $('.a').removeClass('a').addClass('b');
});
$('.b').on('click',function() {
  alert('b');
  $('.b').removeClass('b').addClass('a');
});
每次点击弹出的都是a,要刷新页面后再次点击才弹出b,也就是必须要刷新页面才能改变
请问怎么解决,谢谢各位。

------解决方案--------------------

jQuery(function($){
$('a').toggle(function(){
alert('a');
$(this).removeClass('b').addClass('a');
},function(){
alert('b');
$(this).removeClass('a').addClass('b');
});

});


楼主有一点要搞清,如果你要侦听样式定义变化,你的写法是错误的
------解决方案--------------------
样式最好先定义出来,只要把新的样式定义名称赋值给元素,就可以看到效果了

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://img.renzhe.com/static/js/jquery-1.8.3.min.js"></script>
<title>无标题文档</title>
<style type="text/css">
a{text-decoration:none;color:#f00}
.b{color:#000}
</style>
</head>

<body>
<a href="javascript:;" >this is anchor</a>
<script type="text/javascript">
jQuery(function($){
$('a').click(function(){
$(this).toggleClass('b');
});
});
</script>
</body>
</html>

------解决方案--------------------
$('body').on("click",".a",function(e){
      $(e.currentTarget).removeClass("a").addClass("b")
});

$('body').on("click",".b",function(e){
      $(e.currentTarget).removeClass("b").addClass("a")
});