使用jquery添加字段

时间:2014-09-09 16:39:13

标签: javascript jquery html razor

我试图允许用户使用jquery在我的视图中添加和删除电子邮件字段。无论何时任何一个链接都没有任何反应。

的HTML / CSHTML

<div id="emailSection">
  <ul>
    <li>Email(s) to send notice to.</li>
     <li><input type="email" name="emails[]" /><a href="#" class="remove_field">Remove</a></li>
     <li><a class="add_email_button ui-button" href="#" >Add Another Email</a></li>
  </ul>
</div>

JS

<script type="text/javascript">
    $(document).ready(
        function() {
           ...
            $('.remove_field').on("click", function (e) {
                e.preventDefault();
                $(this).parent('li').remove();
            });
            $('.add_email_button').on('click', function (e) {
                e.preventDefault();
                $(this).insertBefore('<li><input type="email" name="emails[]" /><a href="#" class="remove_field">Remove</a></li>');
            });
        }
    );

</script>

这是fiddle

3 个答案:

答案 0 :(得分:1)

有一些小问题(你添加了新项目和你删除的内容 - 错误的父项),但主要的一点是你应该为点击事件使用委托事件处理程序。他们不关心以后是否添加元素。

JSFiddle:http://jsfiddle.net/TrueBlueAussie/yj6ydbgp/3/

$(document).ready(
    function() {
        $('#emailSection').on('click', '.remove_field', function (e) {
            e.preventDefault();
            $(this).parent('li').remove();
        });
        $('.add_email_button').click(function (e) {
            e.preventDefault();
            $('<li><input type="email" name="emails[]" /><a href="#" class="remove_field">Remove</a></li>').insertBefore(this);
        });
    }
);

他们通过列出事件(在此实例中单击)来工作,冒泡到一个不变的祖先元素(如果没有方便的话,document是默认值),然后应用选择器,然后将您的函数应用于导致事件的任何元素。在您的情况下,您可以使用$('#emailSection').on,因为它是最接近的不变的祖先。

这在大多数情况下也更有效,因为选择器仅在事件时应用,并且仅应用于它通过的元素链。在动态添加元素的地方,委托事件处理程序是处理事件的最佳方式。

答案 1 :(得分:0)

必须以另一种方式使用insertbefore:

$(/* What you need to insert */ ).insertBefore(/* Before what ?*/);

在你的情况下,你必须这样使用:

var html = '<li><input type="email" name="emails[]" /><a href="#" class="remove_field">Remove</a></li>';
$(html).insertBefore( $(this) );

适合我:http://jsfiddle.net/yj6ydbgp/

--------- [编辑] ------------

对于删除:

1 /您需要在父级上创建一个事件,以检查所有新的删除按钮(或者他们在创建后不会获得点击事件)。

2 /你waqnt删除&lt; li>父母,而不是&lt; div>父节点。

新增功能,适用于添加和删除 http://jsfiddle.net/yj6ydbgp/1/

答案 2 :(得分:0)

我知道这应该有用,这里有一些额外的信息:

$(document).ready(
    function() {
        $(document).on("click", '.remove_field' , function (e) {
            e.preventDefault();
            $(this).parent('li').remove();
        });
        $('.add_email_button').on('click', function (e) {
            e.preventDefault();
            var html = '<li><input type="email" name="emails[]" /><a href="#" class="remove_field">Remove</a></li>';
            $(html).insertBefore( $(this) );
        });
    }
);

请注意删除的其他替代方法

$(this).closest('li').remove();

不知道何时使用。

nearest()http://api.jquery.com/closest/

parent()http://api.jquery.com/parent/