【问题标题】:Building dynamic form parts using jQuery使用 jQuery 构建动态表单部件
【发布时间】:2009-05-13 07:39:45
【问题描述】:

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

我正在制作一个表单,希望用户能够在其中添加数量不定的联系人(姓名和电话号码)。我只想显示这些表单字段的一行开始,并允许用户单击一个元素,该元素将添加初始行的副本(当然是空的,并且在返回控制器时使用更新的 id 来操作该数据(ASP.NET MVC 应用程序)。

我找到了一些使用 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 版本运行脚本,它工作得很好。如果我能提供帮助,我宁愿不要退回版本。

有什么想法吗?有没有更好的方法来解决这个问题?它应该很简单,但事实证明它比我希望使用我选择的库更乏味。

【问题讨论】:

    标签: javascript jquery asp.net-mvc


    【解决方案1】:

    Here is an example 的代码。它在 Firefox 3 和 IE 7 中对我来说都很好。代码使用的是 jQuery 1.3.2。如果要编辑代码,只需在 URL 中添加 /edit

    几个想法-

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

    【讨论】:

    • 我在 FF 3 中测试脚本。引用旧脚本在同一个浏览器中工作。该应用程序在 MVC 中,但我真的不认为这应该有所作为。安装了另一个 jQuery 插件。我会尝试删除它,看看那里是否存在冲突。
    • 奇怪...我刚刚重新加载了 VS 并运行了有问题的页面,只是为了验证我看到的行为,它工作正常。我一定有一些事情需要重新开始。所以,不一定是解决方案,但无论如何检查其他 jQuery 冲突对未来来说都是很好的建议。谢谢!
    猜你喜欢
    • 2011-12-09
    • 2010-12-21
    • 2017-04-11
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多