0

現在、JSON Web サービスからドロップダウン リストに色をロードする JQuery プラグインを作成しています。

ドロップダウン リストの背景色は、選択した値に応じて変化します。ほとんどの場合、それは機能しています。定期的な変更では期待どおりに機能しますが、私が抱えている問題は、使用している最初のページの読み込みにtriggerHandler("change");あり、トリガーされますが、ページの読み込み時にドロップダウンリストから選択した値で未定義のエラーが発生しているようです。ドロップダウン リストの色の変更をトリガーしない

私のコードは次のとおりです。

$.fn.bindColorsList = function (options) {

    var defColor = options.defaultColor;
    var svcUrl = options.svcurl;
    //var f_target = options.filterTarget;
    var $this = this;

    $.ajax({
        url: options.svcurl,
        dataType: 'json',
        /*data: { filter: src_filt },*/
        success: function (fonts) { fillcolors(fonts, $this) },
        error: function () { appendError(f_target, "colors failed to load from server") }


    });


    this.on("change", function (event) {
        log($(event.target).attr("id") + " change detected");

        //change ddl dropdown color to reflect selected item ;
        var hcolor = $this.find('option:selected').attr("name");


        $this.attr("style", "background-color:" + hcolor);


    });

function fillcolors(colors, target) {

    $(target).empty();
    $.each(colors, function (i, color) {
        $(target).append("<option name='"+color.HexValue+"' value='" + color.Name + "' style='background-color:"+color.HexValue+"'>"+color.Name+"</option>");
    });
};



//in a seperate file
    $(document).ready(function () {

        $("#dd-font-color").bindColorsList({ svcurl: "/home/colors"});
        $("#dd-back-color").bindColorsList({ svcurl: "/home/colors" });




    });
4

1 に答える 1

1

ちなみに、ドロップダウンにデータを入力するためにAJAXリクエストを実行していますが、これは非同期のものです。この場合success、AJAX リクエストのコールバックでイベントをトリガーする必要があります。

var $this = this;

// Bind the onchange event
$this.on("change", function (event) {
  ..
});

// Populate using AJAX
$.ajax({
  ...
  success: function (fonts) {
    // Populate the values
    fillcolors(fonts, $this);
    // Trigger the event
    $this.trigger("change");
  },
  ...
});

それでおしまい。

于 2012-04-08T11:45:48.203 に答える