简体   繁体   English

通过在中使用JavaScript添加新行<div>

[英]Add new row by using JavaScript in <div>

I want to add new row when the button is clicked. 我想在单击按钮时添加新行。 Below is my code. 下面是我的代码。

<div class="table">
<div id="rows" class="row">

<div id="col1" class="p2">
  <asp:CheckBox id="checkbox1" runat="server" Text="" TextAlign="Right" />
</div>

<div id="col2" class="p3">&nbsp;</div>
<div id="col3" class="p4">
  <asp:TextBox ID="TextBox2" runat="server" Text="2.00"/>
</div>

<div id="col4"class="p5">&nbsp;</div>
<div id="col5" class="p6">
  <asp:TextBox ID="TextBox3" runat="server" Text="1.00"/>
</div>

<div class="row2" style="text-align:center;">
  <button class="clsButton" id="addrow">Add Row</button>
</div>
</div>

below is my jQuery code: 以下是我的jQuery代码:

 var cloneCount = 1;

    //add new row
    $("#addrow").click(function () {
        $('#rows')
        .clone(true)
        .attr('id', 'rows' + cloneCount++, 'class', 'row')
       .insertAfter('[id^=rows]:last');
        return false;
    });

The button does not seems to be working. 该按钮似乎不起作用。 Which part was wrong? 哪一部分错了? I'm really new in JavaScript. 我真的是JavaScript新手。 Im using VisualStudio 2012, in .aspx form and C# language. 我使用.aspx格式和C#语言的VisualStudio 2012。 Thanks for helping! 感谢您的帮助!

function AddRow() {
    var row = document.getElementById("row1");
    var row1 = row.cloneNode(true);
    var box = document.getElementById("table");
    box.appendChild(row1);
}

This is the answer you need I think. 我认为这是您需要的答案。 But it's not the good practice as you'll be duplicating the IDs here. 但这不是一个好习惯,因为您将在此处复制ID。 Use class instead of id . 使用class而不是id

I changed from JavaScript to jQuery. 我从JavaScript更改为jQuery。 And the problem were solved. 解决了问题。 Thanks for helping. 感谢您的帮助。 below is my answer. 以下是我的答案。

 <script type="text/javascript">
    var cloneCount = 1;

    //add new row
    $("#addrow").click(function () {
        $('#row')
        .clone(true)
        .attr('id', 'row' + cloneCount++, 'class', 'row')
       .insertAfter('[id^=row]:last');
        return false;
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM