jquery获取不了ajax动态添加的内容的解决办法

在HTML页面的一个button

1 <div class="ajaxClick">
2     <button>内容</button>
3 </div>

正常点击事件:

1 $(function(){
2     $(".ajaxClick button").click(function(){
3         $(this).html("点击改变");
4     });
5 });

现在通过ajax使得button变成“<button>这是ajax添加的按钮</button>”

 1 function cancel_follow(obj,id) {
 2 
 3     var _this = $(obj);
 4     $.ajax({
 5         type: 'post',
 6         url: 'index.php?app=mobile_follow_designer&act=cancel_follow_designer',
 7         dataType: 'json',
 8         data: {'fid': id},
 9         success: function (result) {
10             if (result.code == 200) {
11                 $(".ajaxClick").html("<button>这是ajax添加的按钮</button>");
12             } else {
13                 $.toast(result.tips, {icon: 0});
14             }
15         }
16     });
17 }

添加后点击事件就失效了,所以解决办法:

1、把点击事件更换成:

1 $(function(){
2     $(".ajaxClick button").click(function(){
3         $(this).html("点击改变");
4     });
5     //  这种写法就可以
6     $(document).on('click', '.ajaxClick button', function() {
7         $(this).html("ajax点击改变");
8     });
9 });

jquery 1.7以前的版本用live,1.7以后的用on

1 $(document).live('.ajaxClick button', function() {
2     $(this).html("ajax点击改变");
3 });

2、把点击事件写在ajax里面:

 1 function cancel_follow(obj,id) {
 2     var _this = $(obj);
 3     $.ajax({
 4         type: 'post',
 5         url: 'index.php?app=mobile_follow_designer&act=cancel_follow_designer',
 6         dataType: 'json',
 7         data: {'fid': id},
 8         success: function (result) {
 9             if (result.code == 200) {
10                 $(".ajaxClick").html("<button>这是ajax添加的按钮</button>");
11             } else {
12                 $.toast(result.tips, {icon: 0});
13             }
14             $(".ajaxClick button").click(function(){
15                 $(this).html("点击改变");
16             });
17         }
18     });
19 }

 

转载于:https://www.cnblogs.com/zhengshize/p/7687069.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值