doudeng2025 2014-05-08 15:43
浏览 45
已采纳

如何防止从AJAX响应中调用相同的jQuery函数并使jQuery功能可行?

I've an HTML form. When the page loads it contains only one <div> I'm calling AJAX function to append <div>. But the javascript which works on HTML content when page loads doesn't work on the content I appended through AJAX. So in order to make the jQuery functionality workable on the content appended through AJAX response. I rewrote the same function in AJAX response. Now the issue arises. The function I wrote in $(document).ready(function{...}) as well as the same function which I wrote in AJAX response gets called. That is the function gets called repeatedly. The function in AJAX gets called exactly the equal no. of <div> I appended. How to avoid this and make the jQuery functionality workable on all the elements including the elements added using AJAX? For your reference I'm giving below my code:

//Below is the function code which I written when document is ready
$(document).ready(function() {
  $('.products').click(function () {
    var table_id = $(this).closest('table').attr('id');

    var no = table_id.match(/\d+/)[0];            
    //var first_row = $(this).closest('table').find('tbody tr:first').attr('id');
    var first_row = $('#'+table_id).find('tbody tr:first').attr('id');

    var new_row = $('#'+first_row).clone();
    //var tbody = $('tbody', '#'+table_id);
    var tbody = $('#' + table_id + ' tbody');
    var n = $('tr', tbody).length  + 1;
    new_row.attr('id', 'reb' + no +'_'+ n);

    $(':input', new_row).not('.prod_list').remove();
    $('select', new_row).attr('name','product_id_'+no+'['+n+']');
    $('select', new_row).attr('id','product_id_'+no+'_'+n);
    $('<button style="color:#C00; opacity: 2;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">&times;</button>').appendTo( $(new_row.find('td:first')) );
    tbody.append(new_row);
    $('.delete').on('click', deleteRow);
   });
});

//Below is the AJAX function code which I'm using to append content. It also contains the same above function code


  function add_rebate_by_product() {
  if($.active > 0) { //or $.active      
    request_inprogress();
  } else {
    var manufacturer_id =  $("#company_id").val();
    var rebate_no       =  $('.rbt').length;

    if ($('.rbt').length>=0) { 
      rebate_no = rebate_no+1;
    }
      $('.add_new_rebate').attr('disabled','disabled');
    }

    $.ajax({
      type: "POST",
      url: "add_rebate_by_product.php",
      data: {'request_type':'ajax', 'op':'create_rebate', 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},  
      beforeSend: function() { 
        $('.load_img').html("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
      },
      success: function(data) {
        if(jQuery.trim(data)=="session_time_out") {
        window.location.href = site_url+'admin/login.php?timeout=1';                
        } else {
          $('.rebate_block').append(data);
          $('.add_new_rebate').removeAttr('disabled');

          $('.states').multiselect({
            includeSelectAllOption: true,
            maxHeight: 150
          });
          $(".date_control").datepicker({
            dateFormat: "yy-mm-dd"
          });
          $('.products').click(function () {
            var table_id = $(this).closest('table').attr('id');

            var no = table_id.match(/\d+/)[0];            
            //var first_row = $(this).closest('table').find('tbody tr:first').attr('id');
            var first_row = $('#'+table_id).find('tbody tr:first').attr('id');

            var new_row = $('#'+first_row).clone();
            //var tbody = $('tbody', '#'+table_id);
            var tbody = $('#' + table_id + ' tbody');
            var n = $('tr', tbody).length  + 1;
            new_row.attr('id', 'reb' + no +'_'+ n);

            $(':input', new_row).not('.prod_list').remove();
            $('select', new_row).attr('name','product_id_'+no+'['+n+']');
            $('select', new_row).attr('id','product_id_'+no+'_'+n);
            $('<button style="color:#C00; opacity: 2;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">&times;</button>').appendTo( $(new_row.find('td:first')) );
            tbody.append(new_row);
            $('.delete').on('click', deleteRow);
            });         
        }
        $('.load').remove();
      }
    });
//}
}

I've written the same javascript function in AJAX response body as when AJAX gets called the javascript object gets destroyed and we need to again recreate the javaceript object in order to make the jQuery functionality workable. But the issue I'm facing is the function is getting called multiple times instead of once only when the request is made for it. Please help me in this regard. Thanks in advance. I you need any further information regarding the question I can provide you the same.

  • 写回答

1条回答 默认 最新

  • donglao7947 2014-05-09 03:39
    关注

    First thing I'd like to point out the wrong thing you are doing is you are writing the same jQuery function twice at different positions in your code. This is an unnecessary code redundancy. It's a very bad style of programming. If you write the function in following fashion you will get everything working fine. Also remove the same function code you have written in AJAX response.

    $(function () {
      $(document).delegate('.products','click',function (e) {
        var table_id = $(this).closest('table').attr('id');
    
        var no = table_id.match(/\d+/)[0];            
        //var first_row = $(this).closest('table').find('tbody tr:first').attr('id');
        var first_row = $('#'+table_id).find('tbody tr:first').attr('id');
    
        var new_row = $('#'+first_row).clone();
        //var tbody = $('tbody', '#'+table_id);
        var tbody = $('#' + table_id + ' tbody');
        var n = $('tr', tbody).length  + 1;
        new_row.attr('id', 'reb' + no +'_'+ n);
    
        $(':input', new_row).not('.prod_list').remove();
        $('select', new_row).attr('name','product_id_'+no+'['+n+']');
        $('select', new_row).attr('id','product_id_'+no+'_'+n);
        $('<button style="color:#C00; opacity: 2;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">&times;</button>').appendTo( $(new_row.find('td:first')) );
        tbody.append(new_row);
        $('.delete').on('click', deleteRow);
    
      });  
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示