代码之家  ›  专栏  ›  技术社区  ›  nkirkes

使用jquery构建动态表单部件

  •  1
  • nkirkes  · 技术社区  · 15 年前

    (希望不会重复;再次尝试提交此问题)

    我正在处理一个表单,在该表单中,我想让用户能够添加一个未定数量的联系人(姓名和电话号码)。我只想显示这些表单字段中的一行,并允许用户单击一个元素,该元素将添加初始行的重复项(当然是空的,并且在返回到控制器(ASP.NET MVC应用程序)时具有用于操作该数据的更新ID)。

    我发现了一些使用jquery库的1.2.x版本的示例,但是我似乎无法让它们中的任何一个使用1.3.2。问题与$.Clone()方法有关。当我在选择器/元素上调用此方法时,页面将进行完全刷新,并向用户显示一个干净的表单。

    我正在使用的当前示例(从 http://devblog.jasonhuck.com/assets/infiniteformrows.html 看起来像:

    桌子-

    <table id="tabdata">
                <thead>
                    <tr>
                        <th>Row</th>
                        <th>Cell 1</th>
                        <th>Cell 2</th>
                        <th>Cell 3</th>
    
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><a id="addnew" href="">Add</a></td>
                        <td><input id="n0_1" name="n0_1" type="text" /></td>
                        <td><input id="n0_2" name="n0_2" type="text" /></td>
    
                        <td><input id="n0_3" name="n0_3" type="text" /></td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
    

    剧本-

    <script type="text/javascript">
        $(function() {
            var newRowNum = 0;
    
            $('#addnew').click(function() {
                newRowNum++;
                var addRow = $(this).parent().parent();
                var newRow = addRow.clone();
                $('input', addRow).val('');
                $('td:first-child', newRow).html(newRowNum);
                $('td:last-child', newRow).html('<a href="" class="remove">Remove<\/a>');
                $('input', newRow).each(function(i) {
                    var newID = newRowNum + '_' + i;
                    $(this).attr('id', newID).attr('name', newID);
                });
                addRow.before(newRow);
    
                $('a.remove', newRow).click(function() {
                    $(this).parent().parent().remove();
                    return false;
                });
    
                return false;
            });
        });
     </script>
    

    当方法状态为“var newrow=addrow.clone();”时,页面将重新加载。不知道为什么,但是在早期的jquery版本中运行脚本,它工作得很好。如果我能帮上忙的话,我宁愿不退回版本。

    有什么想法吗?有更好的方法吗?这本应该很简单,但事实证明,它比我所选择的图书馆更乏味。

    1 回复  |  直到 15 年前
        1
  •  0
  •   Russ Cam    15 年前

    Here is an example 你的代码。在火狐3和IE7中,它对我来说都很好。代码使用jquery 1.3.2。如果要编辑代码,只需添加 /edit 指向URL。

    一些想法-

    • 您在哪个浏览器中查看不起作用的代码?
    • 您使用的其他javascript库是否可能导致冲突?