行克隆无法正常工作

时间:2017-03-03 13:03:39

标签: javascript jquery

我正在尝试添加一个简单的行。以下是我的javascript代码

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

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

3 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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>
		<form action='/results' method="post">
			<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>
		</form>

答案 2 :(得分:2)

你需要修复你的小提琴,以使其工作。

  1. 将缺少的jquery引用添加到您的小提琴中。
  2. 使用结束括号关闭document.ready函数
  3. 我建议你手动将行附加到表中,因为克隆现有行总是给出相同的id即。 (&#39;#Row2&#39;)可能会给你带来麻烦。因此,请随意在按钮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>');
    

    希望这对未来的某些人有所帮助。

相关问题