0

jQuery 1.7.2 を使用して一連のフォーム入力要素を複製しています。各入力要素には id 属性があります。複製された要素がソース要素と同じ id 属性を使用するようにしたいのですが、一意にするためにそれらに番号が追加されます。

私が持っているコードはこれです:

    // Add additional author fields
    jQuery('#addanotherauthor a').click(function () {
        // Clone 'other author' group of fields
        var markUpToClone = jQuery('.other-authors').clone();
        // Set all input values of cloned mark-up to empty, remove 'disabled' attribute
        markUpToClone.find('input').val('').removeAttr('disabled');
        // Ensure cloned inputs have unique id attributes
        var numberOfAdditionalAuthors = $('.other-authors').length.toString();
        markUpToClone.find('input').attr('id', $(this).attr('id') + numberOfAdditionalAuthors);
        // Append emptied clone
        jQuery('#otherauthorscontainer').append(markUpToClone);
        return false;
    });

これを実行すると、複製された要素の id 属性が「undefined1」、「undefined2」などになります。面白いことに、これを行うと次のようになります。

markUpToClone.find('input').attr('id', numberOfAdditionalAuthors);

正しくインクリメントされた数値の ID を返します。そして、私がこれを行うと:

markUpToClone.find('input').attr('id', $(this).attr('id'));

ソース値と同じ ID を返します。しかし、2つを一緒にしようとすると:

markUpToClone.find('input').attr('id', $(this).attr('id') + numberOfAdditionalAuthors);

「undefined1」の問題が発生します。

誰でもこれが失敗しているところを見て、修正を提案できますか?

ありがとう!

4

1 に答える 1

2

の使用はthis文脈から外れています。attr(function(index, attr){})IDの管理に使用しています

// Add additional author fields
    jQuery('#addanotherauthor a').click(function () {
        // Clone 'other author' group of fields
        var markUpToClone = jQuery('.other-authors').clone();
        // Set all input values of cloned mark-up to empty, remove 'disabled' attribute
        var numberOfAdditionalAuthors = $('.other-authors').length/*.toString()*/;// toString() not needed
        markUpToClone.find('input').val('').removeAttr('disabled')
        // Ensure cloned inputs have unique id attributes
                .attr('id', function(i, id){
                        return id + numberOfAdditionalAuthors;
                });


        // Append emptied clone
        jQuery('#otherauthorscontainer').append(markUpToClone);
        return false;
    });
于 2012-06-04T11:39:06.830 に答える