簡體   English   中英

將輸入字段添加到表單中

[英]Adding Input Field to form

我試圖用這個:

小提琴

但似乎他使用的jQuery版本已經過時了。

但是,我在他的代碼中看到的唯一必要的更新是將.live()更改為.on() 但是如果我改變的話,刪除按鈕拒絕工作。

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

任何人都知道為什么?

  1. ID必須是唯一的(這不會造成麻煩)
  2. 新添加的內容需要委派。

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/

看起來它需要重寫,幾個棄用的方法,從字符串創建的動態元素,目標所有parent(),相同的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--;
        }
    });
});

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM