2013-08-03 39 views
0

下面是我擁有的代碼示例。我用'setInterval'加載新內容。這導致我的點擊處理程序不能觸發。setInterval阻止點擊處理程序被觸發

Ajax調用一個名爲 'content.php' 文件,該文件只包含此:

<a class='my_link'>Something here</a> 

這是我的網頁:

<div id="content"> 
<a class='my_link'>Something here</a> 
</div> 
$(document).ready(function(){ 
$('.my_link').click(function() { 
alert($(this).html()); 
return false; 
}); 

function loadLog(){  
    var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20; 
    $.ajax({ 
     url: "content.php", 
     cache: false, 
     success: function(html){   
      $("#content").html(html); //Insert chat log into the #chatbox div    
      var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20; 
      if(newscrollHeight > oldscrollHeight){ 
       $("#content").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div 
      }    
     }, 
    }); 
}; 
setInterval (loadLog, 3000); 
}); 
+0

如果loadLog被調用,'$( 「#內容」)HTML(HTML) ;'會使你的.my_link上的點擊處理程序停止工作。這是你的問題嗎? –

回答

1

既然你添加$('.myLink').click(...後鏈接已經執行,它沒有附加'點擊'處理程序。

您將需要使用委託

$(document.body).on('click', '.my_link', function(e){ 

    alert($(this).html()); 
    return false; 

}); 

瞭解更多關於代表在jQuery documentation

+0

非常感謝你的幫助,像魅力一樣工作! – Jagis

相關問題