简体   繁体   中英

calling .click() script inside another function

Hi I am trying to generate dynamically HTML tables using append(). The way I have written the code is if the user wants to enter the data in the localStorage it first checks if it is empty.If it is empty the code in if block gets executed.If not empty then the else block gets executed.All this code is in the getDetails() JavaScript function. I have given the dynamically generated table id as "myTable".

  <table align="center" id="myTable">

  </table>

  <script>
   function getdetails(){
      if(localStorage.length == 0){
          ......
       }
      else{
          do something ...
      }

      }
  <script>

The issue is that I need to get the row number when I click the table row.For that I have created the following function.

    $(window).load(function() {

     $("#myTable tr").click(function(){
        .....
        });
     });

The above code gets executed (window.load ) when the page refreshes or loads for th first time.But when I add another row in the HTML table( the code exceutes the else block since localStorage is not empty) and click any table row the code doesnt work. Could anyone please tell me on how to get the .click() to work every time.Thanks.

you can bind the events using on keyword to work on the dynamic DOM elements

Try like this:

$("#myTable").on('click','tr',function(){

        //logic here..

 });

Actual problem is you are trying to add click event on row which does not exists when page load.They will load after the execution of script.So the solution for this problem is remove click event from window.load and add it in the script after data population code.

You can also use .on() event of jquery which will work in any case.

Try this:

 $("#myTable tr").click(function(){
      alert('You clicked row '+ ($(this).index()+1) );
 });

Source: Which row number is clicked in a table

Use this

$(document).on('click','#myTable tr',function(){

// your code });

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