2017-03-03 119 views
1

我想添加一个简单的行。以下是我的javascript代码行克隆不工作

$(document).ready(function() { 
    $('#btnAdd').click(function() { 
      var first_row = $('#Row2'); 
      first_row.clone().appendTo('#blacklistgrid'); 
    }); 

我正在使用小提琴https://jsfiddle.net/scxfvu7y/。但该按钮不起作用。我究竟做错了什么?

+0

您知道文档中的ID必须是唯一的吗? – Teemu

+0

按F12打开开发人员控制台,您将看到代码无法工作的原因。 –

+0

https://jsfiddle.net/scxfvu7y/5/ 你错过了jquery cdn –

回答

5
  • 您缺少对jQuery的引用。添加到下面的小提琴版本。
  • 您没有关闭对ready的呼叫。

    $(document).ready(function() { 
        $('#btnAdd').click(function() { 
          var first_row = $('#Row2'); 
         first_row.clone().appendTo('#blacklistgrid'); 
         }); 
    }); // <<< Add this 
    

https://jsfiddle.net/scxfvu7y/4/

2

您没有关闭该文档的支架准备和你的小提琴,你不加载jQuery库。

$(document).ready(function() { 
 
    $('#btnAdd').click(function() { 
 
      var first_row = $('#Row2'); 
 
      first_row.clone().appendTo('#blacklistgrid'); 
 
    }); 
 
    });
td { 
 
    padding-right: 15px 
 
} 
 
.space { 
 
    padding-right: 75px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
\t \t <form action='/results' method="post"> 
 
\t \t \t <table id="blacklistgrid"> 
 
     <tr id="Row1"> 
 
      <td>Week Number</td> 
 
      <td>Oranges Sold</td> 
 
      <td>Apples Sold</td> 
 
     </tr> 
 
     <tr id="Row2"> 
 
      <td> 
 
       <input type="text"/> 
 
      </td> 
 
      <td> 
 
       <input type="text"/> 
 
      </td> 
 
      <td> 
 
       <input type="text"/> 
 
      </td> 
 
     </tr> 
 
    </table> 
 
    <button type="button" id="btnAdd">Add Row!</button> 
 
    </br> 
 
    </br> 
 
    <input type="submit"></input> 
 
\t \t </form>

2

你需要修复您的拨弄下序,使其工作。

  1. 将缺少的jquery引用添加到您的小提琴中。
  2. 关闭与结束的document.ready功能牙套

我建议你到行追加到手动表,因为总是克隆现有行给出相同的ID IE。 ('#Row2'),这可能会在某个时候给你带来麻烦。因此,请随意在按钮Click事件中使用此代码。

var lastrow_index = $('#blacklistgrid tr:last').attr('id').replace(/\D/g,''); 
var currentrow_index = parseInt(lastrow_index + 1); 
$('#blacklistgrid').append('<tr id="'+ currentrow_index +'"><td><input type="text"/></td><td><input type="text"/></td><td><input type="text"/></td></tr>'); 

希望这对未来有帮助。