weixin_33701564 2015-10-13 02:26 采纳率: 0%
浏览 108

jQuery Ajax:自动刷新

In my Ajax success function i created button and on click i am calling a function. The problem: The page reloads based on the timer in set interval but when i click the button it will call the function based on the number of times the page reloaded.

For example: If page reloads 5 times and then i call a function on clicking that button-it will call that function 5 times. if it reloads 10 times then function call is for 10 times.

Please advice what i am doing wrong?

Here is the code:

        $(document).ready(
                function() {
               setInterval(function() {                  
                         $.ajax({
                  type: 'GET',
                   url: 'Refresh',
              success: function(data) {
                 var trHTML = '';
            $.each(data, function(i, item) {
    var buttonVar = ('<button id="bt21" class="btn121">' + "STOP" + '</button>');
          trHTML += '<tr><td>'+buttonVar+'</td></tr>'
            });
          $('#test1').append(trHTML);

          $(document).on('click','#bt21', function(event) {
         var rownum1 = $(this).closest('tr').index();
       stopTest(data[rownum1].process_id);
         });
             }
         });
      }, 5000);
  });
  • 写回答

3条回答 默认 最新

  • weixin_33690367 2015-10-13 02:36
    关注

    You have set the AJAX call to be made every 5 seconds. Each time time this function is called, you are also attaching the click event on the button you append. So there will be multiple event handlers attached to the same element. You need to clear any existing event handlers on that element before you attach another if you want to stick to your current code. Here's how to do it:

    $(document).off('click', '#bt21');
    $(document).on('click','#bt21', function(event) {
         var rownum1 = $(this).closest('tr').index();
       stopTest(data[rownum1].process_id);
         });
    
    评论

报告相同问题?