0

私はその JavaScript と jQuery のすべての初心者です。私のコーディングや汚いスタイルの愚かな誤りを許してください. 経験豊富な方からの建設的なフィードバックをお待ちしております。

新しい選択メニューなど、いくつかの jQuery 要素を動的に追加しようとしています。私の例では、ユーザーはカスタマイズしたい車の数を決定し、それに基づいて、選択した車ごとに 1 つの新しい選択メニューを作成したいと考えています。

ユーザーが「2台の車」を選択すると、jQueryが2つの新しい選択メニューを追加するようにしました。しかし、私の問題は、これらのメニューが jQuery スタイルではなくなったことです。

ここで何が間違っていますか?選択した車の数に基づいて「for ループ」に新しいメニューを追加することも可能ですか?

これが私のコードです:

<script type="text/javascript">

    $('#select-choice-1').live( "change", function(event, ui) {
        var valuee = $(this).val();

        if (valuee == '2') ($('<label for="select-choice-2" class="select">Color of car #1</label>' +
                                          '<select name="select-choice-2" id="select-choice-2">'+
                                          '<option value="red">red</option>'+
                                          '<option value="blue">blue</option>'+
                                          '</select><br><br>' +
                              '<label for="select-choice-3" class="select">Color of car #2</label>' +
                                          '<select name="select-choice-3" id="select-choice-3">'+
                                          '<option value="green">green</option>'+
                                          '<option value="yellow">yellow</option>'+
                                          '</select>').appendTo('#site'));
        if (valuee == '3') ($('<h1>Test</h1>').appendTo('#site'));

    });
    </script>

そして、これがhtmlページです:

<div id="site" data-role="fieldcontain">    

    <label for="select-choice-1" class="select">Number of cars</label>
    <select name="select-choice-1" id="select-choice-1">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>


    </div><!-- "site" -->
4

1 に答える 1

0
        $('#site').delegate("#select-choice-1", "change", function(event, ui) {
           var valuee = $(this).val();
           var constructhtml = '';
             if (valuee == '2') {
               constructhtml +='<label for="select-choice-2" class="select">Color of car #1</label>' +   '<select name="select-choice-2" id="select-choice-2">'+ '<option value="red">red</option>'+ '<option value="blue">blue</option>'+ '</select><br><br>' + '<label for="select-choice-3" class="select">Color of car #2</label>' + '<select name="select-choice-3" id="select-choice-3">'+ '<option value="green">green</option>'+ '<option value="yellow">yellow</option>'+ '</select>';
             }else if (valuee == '3') {
               constructhtml +='<h1>Test</h1>';
             }
    $('#site').append(constructhtml);
     });

動的に追加された選択メニューを作成する OP の必要性

この div をページの一番下に配置します

<div id="selectcontainer"></div>

$(document).ready(function(){

var str = '';
str+='<select>';
   for(i=1;i<=10;i++){
    str+='<option value='"+i+"'>'"+i+"'</option>';

  }   
str+='</select>';
 $('#selectcontainer').html(str);
});
于 2012-11-07T08:34:58.427 に答える