2017-03-03 125 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>'); 

希望這對未來有幫助。