将输入字段添加到表单中

时间:2013-05-12 02:03:42

标签: javascript jquery

我试图用这个:

Fiddle

但似乎他使用的jQuery版本已经过时了。

但是,我在其代码中看到的唯一必要更新是将.live()更改为.on()。但如果我改变了,删除按钮就不起作用了。

    $('#remScnt').on('click', function() { 
            if( i > 2 ) {
                    $(this).parents('p').remove();
                    i--;
            }
            return false;
    });

任何人都知道为什么?

2 个答案:

答案 0 :(得分:1)

  1. ID必须是唯一的(这不会造成麻烦)
  2. 新添加的内容需要委派。

  3. 的jQuery

    $(function () {
        var scntDiv = $('.p_scents');
        var i = $('.p_scents p').length + 1;
    
        $('#addScnt').on('click', function () {
            $('<p><label for="p_scnts"><input type="text" class="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
            i++;
            return false;
        });
    
        $('.p_scents').on('click', '.remScnt', function () {
            if (i > 2) {
                $(this).parents('p').remove();
                i--;
            }
            return false;
        });
    });
    

    HTML

    <h2><a href="#" id="addScnt">Add Another Input Box</a></h2>
    
    <div class="p_scents">
        <p>
            <label for="p_scnts">
                <input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />
            </label>
        </p>
    </div>
    

    完美无缺:http://jsfiddle.net/uFkPx/

答案 1 :(得分:1)

看起来需要重写,几个弃用的方法,从字符串创建的动态元素,定位所有的父(),相同的ID等:

$(function () {
    var scntDiv = $('#p_scents'),
        i       = $('#p_scents p').length + 1;

    $('#addScnt').on('click', function (e) {
        e.preventDefault();
        var p = $('<p />'),
            l = $('<label />', {for: 'inp_'+i}),
            j = $('<input />', {type: 'text', 
                                id: 'inp_'+i, 
                                size: 20,
                                name: 'p_scnt_' + i,
                                placeholder: 'Input Value'
                               }),
            a = $('<a />', {href : '#', 
                            id: 'remScnt_' + i,
                            'class' : 'remScnt',
                            text: 'Remove'
                           });

        p.append(l.append(j), a).appendTo(scntDiv);
        i++;
    });

    scntDiv.on('click', '.remScnt', function (e) {
        e.preventDefault();
        if (i > 2) {
            $(this).closest('p').remove();
            i--;
        }
    });
});

FIDDLE

相关问题