简体   繁体   中英

Jquery script stops working when another script reload page

I have this html:

<td>
  <div class="status">1</div>
  <span class="fa fa-times-circle" aria-hidden="true"></span>
</td>

I have this script:

<script>
  $('.status:contains("1") + span').removeClass('fa-times-circle').addClass('fa-sun-o');
</script>

The script basically removes and adds class depending on the text of the div 1 or 0. However, the script works only for 10 seconds then it reverts back to the default class which shows fa-times-circle. It stop when another script (see below) reload the data every 10-second interval.

<script>
  (function updateStafftable() {
    $.get('sql/staff-status.php', function(data) {
      $('.table-staffs').html(data);
      setTimeout(updateStafftable, 10000);
    });
  })();
</script>

Do you guys know why? Also, an important detail I would like to point out is that the html that I mentioned in the beginning is in the 'staff-status.php' which reload every 10-second interval. I just don't understand why this happens.

Your way is not good but if you want to acheive your goal with minimal changes then put that script in success of ajax call

<script>
  (function updateStafftable() {
    $.get('sql/staff-status.php', function(data) {
      $('.table-staffs').html(data);
      $('.status:contains("1") + span').removeClass('fa-times-circle').addClass('fa-sun-o');
      setTimeout(updateStafftable, 10000);
    });
  })();
</script>

Better way

edit logic in staff-status.php by putting if condition to assign class based on status like

   ...    
   if($status == 1){
     $class= 'fa-sun-o';
    }else{
     $class= 'fa-times-circle';
    }
    ....
    <td>
      <div class="status">$status</div>
      <span class="fa $class" aria-hidden="true"></span>
    </td>
    ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM