重新加载$(document).ready(function()重新加载ajax页面后

问题描述:

我有一个常见的js文件 我重新加载ajax请求中的html页面后,我不能访问这个文件中的函数,常见的JS函数$(文件)。就绪(函数() 怎样才能访问这些和火在共同文件中的函数

COMMON JS:

$(document).ready(function() { 

$(".agree_btn").click(function(){ 
     alert(123);    
    }); 

}); 

功能在PHTML

$('.loadMoreAnswers').live('click', function(event) { 

      var location_id = $(this).attr('location_id'); 
      var counter= $(this).attr('counter'); 
       $('#loadingAnswer').show(); 

     $.ajax({ 
      type: 'POST', 
      url: '/daleel/loadmore', 
      data: 'location_id='+location_id+'&part='+'answers'+'&answerCounter='+counter, //with the page number as a parameter 
      success: function(msg){ 

       if(msg.length!=0) //if no errors 
       { $(this).parent().load("view") 
        $('#loadingAnswer').remove(); 
        counter+=5; 
        $('#profile-page-answer').append(msg); 

       } 
       else $("#loadingAnswer").remove(); 

      }, 
      dataType: 'html' 
     }); 

       }); 

其呈现类似这样的HTML:

<a agreed="no" agreed-content-id="63066" class="agree_btn" id="agree-a63066"> 
Agree 
    </a> 

但是,当我在这个链接 点击它并不在公共JS文件运行功能

重新绑定在阿贾克斯成功的单击事件处理程序

success: function(msg){ 
//your code 
$(".agree_btn").bind('click'); 
} 

,或者您可以使用delegate jQuery的版本低于1.7像

$(document).delegate(".agree_btn",'click',function(e){ 
//your code 
}); 

,或者你使用jQuery版本1.7+使用on方法

$(document).on("click",".agree_btn",function(e){ 
//your code 
}); 

不使用.live其弃用docs

在jQuery 1.7中,.live()方法已过时。使用.on()连接到事件处理程序 。老版本jQuery的用户应该优先使用 .delegate(),而不是.live()。

+0

在哪里把.success(fucntion()){} – KJA

+0

@KJA sry为混乱成功处理已经在你的ajax调用中添加我已经编辑了答案 – Rafay

+0

它不与通用js中的函数绑定。或者我不明白它好 – KJA

使用live()内常见的js文件。对于如

$('selector').click(function(){ 
//function body 
}) 

,而不是这个用

$('selector').live('click', function(){ 
//function body 
}) 
+3

从头开始,你可能需要使用。对(事件[,选择] [数据],处理器(eventObject)传递),因为这种方法是不推荐给.live()之前版本1.7,并不会支持jQuery的未来版本http://api.jquery.com/live/ – mayrs

在ajax完成后,嵌入了document.ready函数。在ajax调用之后,它将在页面上重新注册脚本。

如:

$.ajax({ 
      url: 'deleteEntry', 
      data: {'ids': JSON.stringify(getList)}, 
      async: true, 
      success: function (data) { 
       location.reload(); 
      }, 
      error: function (data) { 
       alert('error'); 
      }, 
      complete: function (data) { 
       //add your script in body here 
      } 
     });