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);
    
      });  
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA