Jquery and adding row to table

后端 未结 2 785
小蘑菇
小蘑菇 2020-12-30 09:48

I have the following jquery code.

var destTable = $(\"#numbers\");
$(document).ready(function() {
  $(\"#btnAdd\").click(function() {
   //Take the text, and         


        
相关标签:
2条回答
  • 2020-12-30 09:49

    Keep the reference inside document.ready:

    $(document).ready(function() {
      var destTable = $("#numbers");
      $("#btnAdd").click(function() {
       //Take the text, and also the ddl value and insert as table row.
       var newRow = $("<tr><td>hi</td></tr>");
       $("#numbers").append(newRow);
      });
    });
    

    The point of document.ready is to wait for the DOM to be ready; if you try doing $('#numbers'); outside of it (and the code does not appear after the element in the document) the DOM will not have yet created this element so you won't have a proper reference to it.

    Once you do this, you should be able to do:

    destTable.append(newRow);
    

    Inside the click function. As a last note, however, it is a common and accepted practice to preface variables that represent jQuery sets with a $. So this is best:

    var $destTable = $("#numbers");
    
    0 讨论(0)
  • 2020-12-30 09:49

    Your can use appendTo like this :

    $("<tr><td>Hello</td><tr>").appendTo("#MyTable > tbody") 
    
    0 讨论(0)
提交回复
热议问题