jQuery .click() not working?

前端 未结 4 1069
挽巷
挽巷 2021-01-14 03:57

I generate the set of buttons within html table as follows and then I want to call to function when it click.

$.each(childData, function(key, item) {
    va         


        
相关标签:
4条回答
  • 2021-01-14 04:20

    You need to use event delegation.

    If your table has an id of "button-table", you can create an event handler like so:

    $("#button-table").on("click",function(e){
        var target = e.target;
        console.log($(target).attr("data-id"));
    });
    
    0 讨论(0)
  • 2021-01-14 04:42

    Do you want it this way? I have given code for adding an entire table.Check this out

    function generate_table() {
      // get the reference for the body
      var body = document.getElementsByTagName("body")[0];
     
      // creates a <table> element and a <tbody> element
      var tbl     = document.createElement("table");
      var tblBody = document.createElement("tbody");
     
      // creating all cells
      for (var i = 0; i < 2; i++) {
        // creates a table row
        var row = document.createElement("tr");
     
        for (var j = 0; j < 2; j++) {
          // Create a <td> element and a text node, make the text
          // node the contents of the <td>, and put the <td> at
          // the end of the table row
          var cell = document.createElement("td");
          var cellText = document.createTextNode("cell in row "+i+", column "+j);
          cell.appendChild(cellText);
          row.appendChild(cell);
        }
     
        // add the row to the end of the table body
        tblBody.appendChild(row);
      }
     
      // put the <tbody> in the <table>
      tbl.appendChild(tblBody);
      // appends <table> into <body>
      body.appendChild(tbl);
      // sets the border attribute of tbl to 2;
      tbl.setAttribute("border", "2");
    }
    <input type="button" value="Generate a table." onclick="generate_table()">

    0 讨论(0)
  • 2021-01-14 04:46

    Delegate the event to static parent:

    $(div).on("click", ".download", function(){  
    

    Here div can be the static parent which was available when page was loaded at first load. Although document or body can also be used in place of div.


    As you have not presented how you create div element but one thing has to be noticed that you are generating an invalid markup. As a td element can't be a child of div but table's tr.

    0 讨论(0)
  • 2021-01-14 04:47

    Try this:

    $(document).on('click', '.download', function(){ 
         // Your Code
    });
    
    0 讨论(0)
提交回复
热议问题