3

ここに私のHTMLがあります::

<fieldset>
    <legend>Attributes</legend>

    <div class="attr_container">
        <div class="attr_entry existent row">
            <div class="half">
                <label for="attribute[]">Attribute</label>
                <input id="attribute" maxlength="50" required="required" name="attribute[]" type="text">                
                <p>
                    <a href="javascript:void(0)" class="add_attr"><i class="fa fa-plus-circle"></i> Add Another Attribute</a> 
                    <span class="remove">| 
                    <a href="javascript:void(0)" class="remove_attr"><i class="fa fa-minus-circle"></i> Remove</a></span>
                </p>
            </div>
            <div class="half">
                <label for="designator">Is this attribute a designator?</label>             <input checked="checked" name="designator[0]" type="radio" value="0" id="designator[0]"> No
                <input name="designator[0]" type="radio" value="1" id="designator[]"> Yes
            </div>
        </div>
    </div>

</fieldset>

これが私のjQueryです:

    $('.add_attr').click(function() {
        // clone and add
        $( ".attr_entry:first" ).clone(true).removeClass('existent').insertAfter( ".attr_entry:last" );
    });

    $('.remove_attr').click(function() {
        // remove entry
        if($(this).parents('.attr_entry').first().hasClass('existent')) {
            alert('You can not remove the first attribute entry.');
        } else {
            $(this).parents(".attr_entry").first().remove();
        }
    });

したがって、これを複製するときに、 name 属性を .. に変更する方法を知りたいdesignator[1]ので、それに追加します。最後に追加されたクローンの後にクローンを作成して挿入する方法がわかりません。

ラジオボタンの配列を受け入れる方法を理解するために参照したHTMLは次のとおりです。

ラジオボタン + 配列要素

PHP の for ループで実行できる属性を知り、それに属する適切な指定子を取得する必要があるためです。

助けてくれてありがとう!

4

2 に答える 2

4

$('.attr_entry')存在する要素の数を評価することで、新しいインデックスを取得できます。次に、 と を組み合わせfind()prop()、ラジオ ボタンの名前を設定できます。

clone()次のように行を修正します。

var newIndex = $('.attr_entry').length;
$('.attr_entry:first').clone(true).removeClass('existent').insertAfter('.attr_entry:last').find('input[type="radio"]').prop('name', 'designator['+newIndex+']');

jsFiddle デモ

また、要素の属性は一意である必要があるため、(同じ方法idを使用して) 同時に更新することを検討することをお勧めします。prop()

于 2014-01-15T21:24:01.317 に答える
2

jquery の clone にあまり慣れていないattr()関数を使用して属性を設定できます。

したがって、コードは次のようになります。

var designatorIndex = 0;
$('.add_attr').click(function() {
    // clone and add

    var myVar = $( ".attr_entry:first" ).clone(true).removeClass('existent');

    $(myVar).attr('name', 'designator' + designatorIndex );
    $(myVar).id('designator' + designatorIndex);
    designatorIndex++;
    $(myVar).insertAfter( ".attr_entry:last" );
});
于 2014-01-15T21:29:30.900 に答える