0

我是所有 JavaScript 和 jQuery-Stuff 的新手。请原谅我的编码或肮脏风格的任何愚蠢错误。我很高兴收到您经验丰富的所有建设性反馈。

我尝试动态添加一些 jQuery 元素,比如一些新的选择菜单。在我的示例中,用户将决定他想要定制多少辆汽车,并在此基础上为每辆选择的汽车创建一个新的选择菜单。

我让它工作,如果用户选择“2 辆车”,jQuery 将添加两个新的选择菜单。但我的问题是这些菜单不再是 jQuery 样式了。

我在这里做错了什么?是否也可以根据选择的汽车数量在“for-loop”中添加新菜单?

这是我的代码:

<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 回答