YU FENG
YU FENG

Reputation: 888

Javascript: does not work when combine JQuery click with setInterval

I create a clickable table but when I add setInterval to reload this table in every 1000, the click event will stop working. Here is the code:

JQuery & Javascript parts:

<head>
    <script type="text/javascript">
    //Set the timer 
    var myTimer = setInterval(function(){showTableContent(),1000});

    //Add click 
    $(document).ready(function () {
       var idForTableRowInfor = "#" + $("div div div table").attr('id');
       $(idForTableRowInfor).click(function () {
           alert('row was clicked');
        });
    })

    //Function of showTableContent()
    function showTableContent() 
    {
      var body = plugin().USBInforArray; //Call FireBreath plugin
      document.getElementById('tableInfor').innerHTML = body;
    }
    </script>
</head>

HTML parts:

...   
<div id="wrapper">
    <div class="mainContent">
        <div id="USBDetectingTable" align="center">
           <table id="tableInfor" border="1">
           </table>
        </div> ...

When I get rid of setInterval everything works fine, but as long as I add into that function, it stops calling click event. Thanks !!!

Upvotes: 2

Views: 834

Answers (2)

epascarello
epascarello

Reputation: 207511

The click no longer works because you are removing the rows and the click is no longer attached.

Learn about the power of .on( events [, selector ] [, data ], handler(eventObject) )

$("#tableInfor").on("click", idForTableRowInfor, function () {
       alert('row was clicked');
});

Upvotes: 4

Rooster
Rooster

Reputation: 10077

var myTimer = setInterval(function(){showTableContent(),1000});

should be

var myTimer = setInterval(function(){showTableContent()},1000);

Upvotes: 1

Related Questions