0

このソースに基づいて、次のコードを使用して入力フィールドをフォームに動的に追加します。

http://www.infotuts.com/dynamically-add-input-fields-to-form-jquery/

ここに私のコードの一部があります:

$(document).ready(function(){
    var counter = 2;
    $("#btnAddIngredients").click(function () {
        var newIngredientsData = $(document.createElement('div'))
            .attr("id", 'ingredientsData' + counter);
        newIngredientsData.html('<div id="ingredientsData'+ counter + '" class="row">' +
                    '<div class="col-ingredients">#'+ counter + ' : <select id="ingredient'+ counter + '" name="ingredient'+ counter + '" class="selectIngredients"><select/></div>' +
                    '<div class="col-extra"><input type="text" name="extra'+ counter + '" id="extra'+ counter + '" size="30" maxlength="100" /></div>' + 
                    '<div class="col-quantity"><input type="text" name="quantity'+ counter + '" id="quantity'+ counter + '" size="5" maxlength="30" /></div>' +
                    '<div class="col-unit"><select id="unit'+ counter + '" name="unit'+ counter + '" class="selectUnit"><select/></div>'+
                    '</div>');
        newIngredientsData.appendTo("#ingredientsList");
        counter++;
    });

    $(".selectIngredients").live("click",function () {
        $(this).empty();
        $(this).append('<option value="">Loading...</option>');
        $.post("getdata.php", {what: "ingredients"},
               function (data){
               alert(data);
               $(this).append(data);
               }
               ,"html");
    });
});

私が期待しているのは、クリックするたびに選択した値が入力されることですが"<option value="">Loading...</option>"、最初に追加したのは だけです。それ$(this).append(data)はそれの仕事をしなかったようです。何も追加されていません。その上のアラート(データ)には、追加する必要があるコンテンツが正しく表示されます。

たとえば、選択$(this).append(data);$("#ingredients1").append(data);たデータは正しくロードされますが、使用するとロードされません$(this).append(data);

ここで何が問題なのですか?なぜ追加しますか。関数 (data){} では機能しませんが、前述の$(this).append('<option value="">Loading...</option>');機能は毎回正しく機能しますか?

4

3 に答える 3

1

$(this)あなたのajax応答では、ウィンドウではなく<select>.

于 2013-07-02T14:56:56.657 に答える