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

时间:2014-05-08 15:43:51

标签: javascript php jquery ajax append

我有一个HTML表单。当页面加载时,它只包含一个<div>我正在调用AJAX函数来追加<div>。但是当页面加载时对HTML内容起作用的javascript对我通过AJAX添加的内容不起作用。因此,为了使jQuery功能在通过AJAX响应附加的内容上可行。我在AJAX响应中重写了相同的函数。现在问题出现了。我在$(document).ready(function{...})中编写的函数以及我在AJAX响应中编写的函数被调用。那就是重复调用函数。 AJAX中的函数被称为完全相等的no。我附加的<div>。如何避免这种情况并使jQuery功能适用于所有元素,包括使用AJAX添加的元素?供我参考,我在下面给出了我的代码:

//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();
      }
    });
//}
}

我在AJAX响应体中编写了相同的javascript函数,因为调用AJAX时javascript对象被破坏,我们需要再次重新创建javaceript对象以使jQuery功能可行。但是我面临的问题是函数被多次调用,而不是仅在为其发出请求时调用一次。请帮助我这方面。提前致谢。我还需要有关我可以为您提供相同问题的任何进一步信息。

1 个答案:

答案 0 :(得分:1)

首先我要指出你正在做的错误是你在代码中的不同位置两次编写相同的jQuery函数。这是不必要的代码冗余。这是一种非常糟糕的编程风格。如果以下列方式编写函数,您将获得一切正常工作。同时删除您在AJAX响应中编写的相同功能代码。

$(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);

  });  
});