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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM