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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog