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

标签 jquery

我有一个通用的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/

相关文章:

javascript - Angular 形 Material 没有 Angular 形 Material 的切屑效果

jquery - Python Flask 获取json数据显示

javascript - jquery : access element inside an angular *ngIf directive

javascript - 如何防止在 React 应用程序中拖放图像?

php - 将 jQuery 淡入或滚动效果应用于 Facebook Like Newsfeed

npm 安装后设置 jQuery

jquery.ajax html 响应链接未运行

javascript - 无法理解为什么此验证未按预期工作

jQuery if 语句将 div 类更改为另一个 not 类

jquery - jQuery 延迟和 Backbone 保存成功方法的问题