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