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);
         });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法
  • ¥15 dnat基础问题,本机发出,别人返回的包,不能命中