1

このスニペットを使用してボタンがクリックされたときに、フォーム内のセクションに HTML を追加する関数があります。

function add_series() {
    $(document).on("click", "a.add-another-series", function(e) {
        e.preventDefault();

        // Get the containing div that we will append the retrieved HTML to
        $container = $(this).parent().parent().parent().parent();

        // Get the HTML via ajax and append it to the containing div
        $.get('ajax/add-series/' + study_number + '/' + series_number, function(data){
            $container.append(data);
        });
     });
}

以下は、AJAX を介して呼び出し元の関数に返される (省略された) HTML 構造です (CAPS は、このテキストが変数であることを示します)。

<div class="series" data-study-number="STUDY_NUMBER" data-series-number="SERIES_NUMBER">        
    <h4>series SERIES_NUMBER</h4>

    <div class="row">
        <div id="RANDOM_ID" class="small-12 columns large-centered uploader">&nbsp;</div>
    </div>                          
</div>

これは正常に機能し、期待どおりにページに表示されます。

私がする必要があるのは、最初の関数内から id=RANDOM_ID で div を取得することです (この質問の冒頭にある「クリック時」のもの)。テストするために、次のセレクターを使用してすべての .series div を取得しようとしました。

$series_divs = $('.study[data-study-number="' + STUDY_NUMBER + '"]').find('.content').find('.series');

これは、.append() 呼び出しの前に存在した .series div のみを返すようです。追加したばかりのものは返されません。ここで何か間違ったことをしていますか?

4

1 に答える 1

1

次のようなことを試してください:

$(document).on("click", "a.add-another-series", function(e) {
    var $container = $(this).parent().parent().parent().parent();

    e.preventDefault();

    $.get('ajax/add-series/' + study_number + '/' + series_number)
    .then(function(data){
        var $data = $(data),
            id = $data.find(".row div").attr("id");

        $container.append($data);

        // Now something with id. Maybe call a function with it?
    });
});

ノート

  • の目的は何function add_series()ですか? イベント ハンドラーを含む関数はあまり使用されないため、削除しました。
  • var変数を忘れました。
  • の代わりに.parent().parent().parent().parent()、で作業してみてください.closest()
  • .find()呼び出しをチェーンする必要はありません。.find('.content').find('.series')と同等find('.content .series')です。
  • どこでstudy_number、どこseries_numberから来たのですか?
于 2013-05-11T10:45:49.347 に答える