0

I've created a dynamic dropdown list with jQuery and JavaScript. I'm hoping someone can take a look and let me know if this is an appropriate way to handle this type of task. I'm specifically curious to know if this code is scalable, and will it perform well? Next, would it be suggested to use a switch statement instead of several if statements in the JavaScript I have below? If so, why? I'd like to store this to be reused anytime I implement a solution like this, but as I'm new to JavaScript I don't completely trust my work yet.

JSFIDDLE: http://jsfiddle.net/6vrpF/

HTML:

<select id='parent'>
  <option value='test'>test</option>
  <option value='sure'>sure</option>
  <option value='cool'>cool</option>
  <option value='best'>best</option>
</select>

<select id='child'>
</select>

JavaScript:

function newDropdown()
{
   var html = ""
   for(i=0; i<arguments.length; i++)
   {
     html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
   }
   $("#child").append(html)
}

$("#parent").on("change",function(){
  $('#child').text("")
  var selection = $("#parent").val()
  if(selection == 'test') {newDropdown('a','b','c')}
  if(selection == 'sure') {newDropdown('d','e','f')}
  if(selection == 'cool') {newDropdown('g','h','i')}
  if(selection == 'best') {newDropdown('j','k','l')}
});
4

1 に答える 1

2

フィドル http://jsfiddle.net/6vrpF/4/を更新しました

var parentChild = {
    "test" :['a','b','c'],
    "sure" :['d','e','f'],
    "cool" :['g','h','i'],
    "best" :['j','k','l']
};

function newDropdown()
{
    var html = ""
    for(i=0; i<arguments.length; i++)
    {
        html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
    }
    $("#child").append(html)
}

$("#parent").on("change",function(){
    $('#child').text("")
    var selection = $("#parent").val();
    newDropdown( parentChild[selection].join(",") );
});

上記の/定義されているように、データを JSON 形式で取得する必要があります

編集:これは、オプションを1つずつ提供する更新されたフィドルです http://jsfiddle.net/6vrpF/6/

var parentChild = {
    "test" :['a','b','c'],
    "sure" :['d','e','f'],
    "cool" :['g','h','i'],
    "best" :['j','k','l']
};

function newDropdown()
{
    var array = arguments[0];
    var html = ""
    for(i=0; i<array.length; i++)
    {
        html += "<option value='"+array[i]+"'>"+array[i]+"</option>"
    }
    $("#child").append(html)
}

$("#parent").on("change",function(){
    $('#child').text("")
    var selection = $("#parent").val();
    newDropdown( parentChild[selection] );
});
于 2013-04-27T20:05:47.513 に答える