2012-04-30 472 views
4

我有一個常見的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文件運行功能

回答

7

重新綁定在阿賈克斯成功的單擊事件處理程序

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

0

使用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

0

在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 
      } 
     });