我有一个通用的js文件 在ajax请求中重新加载html页面后,我无法访问该文件中的函数,$(document).ready(function()之间的常见JS函数 如何访问它们并触发公共(public)文件中的函数 示例:
常见的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>
但是当我点击这个链接时 它不运行 Common JS 文件中的函数
最佳答案
在ajax成功后重新绑定(bind)点击事件处理程序
success: function(msg){
//your code
$(".agree_btn").bind('click');
}
或者您可以使用delegate
对于低于 1.7 的 jQuery 版本,例如
$(document).delegate(".agree_btn",'click',function(e){
//your code
});
或者您正在使用 jQuery 版本 1.7+ 使用 on
方法
$(document).on("click",".agree_btn",function(e){
//your code
});
不要使用已弃用的.live
docs
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
关于jquery - Reload $(document).ready(function() ajax页面重新加载后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10380005/