Help: Цикл для динамического <option>получения его из массива - PullRequest
0 голосов
/ 17 сентября 2009

Мне нужна помощь в моем коде, я не могу понять, как зациклить значения из массива и поместить их в список / меню. Мне нужно зациклить массив roomType и объединить его со скоростью, чтобы она выглядела примерно так (например, Single Room (980.00)), значения roomType и rate будут динамическими для каждой опции.

пожалуйста, посмотрите мой код и дайте мне знать, если мой подход правильный.

Спасибо.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

 <script type="text/javascript">

 $(document).ready(function() {


 $(function() {      

  $('#HasCart_TetrisHotel').ready(function() {

/*   var hotel = HotelQuery('TetrisHotel');
   $('#HasCart_TetrisHotel .hotName').append(hotel.name);
   $('#HasCart_TetrisHotel .hotDesc').append(hotel.desc);
   $('#HasCart_TetrisHotel .hotMenu').append('<select name="price">' + 

    $.each(hotel.roomType, function( intIndex, objValue ){

     $(this).append(
      $( "<option value='" + hotel.price + "' >" + hotel.roomType + "</option>" )
     );

    });


   + '</select>'); */ 


   var hotel = HotelQuery('TetrisHotel');
   $('#HasCart_TetrisHotel .hotName').append(hotel.name);
   $('#HasCart_TetrisHotel .hotDesc').append(hotel.desc);
   $('#HasCart_TetrisHotel .hotMenu').append('<select name="price">' +  '</select>');  


   var hotel = HotelQuery('ParadiseInn');
   $('#HasCart_ParadiseInn .hotName').append(hotel.name);
   $('#HasCart_ParadiseInn .hotDesc').append(hotel.desc);
   $('#HasCart_ParadiseInn .hotMenu').append('<select name="price">' +  '</select>'); 

   var hotel = HotelQuery('JamstoneInn');
   $('#HasCart_JamstoneInn .hotName').append(hotel.name);
   $('#HasCart_JamstoneInn .hotDesc').append(hotel.desc);
   $('#HasCart_JamstoneInn .hotMenu').append('<select name="price">' +  '</select>'); 


  });

 });








  function HotelQuery(HotelName) {
   switch (HotelName) {
    case 'TimelessHotel': 
     var strHotelName = 'Timeless Hotel';
     var strHotelDesc = 'Hotel Description Timeless Hotel';
     var strHotelRate = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00'];
     var strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person'];    
    ; //end Timeless Hotel

case 'ParadiseInn': 
 var strHotelName = 'Paradise Inn';
 var strHotelDesc = 'Hotel Description Paradise Inn';
 var strHotelRate = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00'];
 var strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person'];    
break; //end Paradise Inn

case 'TetrisHotel': 
 var strHotelName = 'Tetris Hotel';
 var strHotelDesc = 'Hotel Description Tetris Hotel';
 var strHotelRate = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00'];
 var strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person'];  
 break; //end Tetris Hotel 

case 'JamstoneInn': 
 var strHotelName = 'Jamstone Inn';
 var strHotelDesc = 'Hotel Description Jamstone Inn';
 var strHotelRate = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00'];
 var strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person'];    
break; //end Jamstone Inn 
}
return {
          name: strHotelName,
          desc: strHotelDesc,
          rate: strHotelRate,
          roomType: strHotelRoomType 
       }; 
};


 });

   </script>     

<title>hotel query</title>
</head>

<body>


 <div id="HasCart_TetrisHotel">
     <table width="380px" border="1" cellspacing="3" cellpadding="0">
          <tr>
            <td class="hotName"></td>
            <td class="hotDesc">&nbsp;</td>
            <td class="hotMenu"></td>
          </tr>
        </table>
    </div>

   <div id="HasCart_ParadiseInn">
     <table width="380px" border="1" cellspacing="3" cellpadding="0">
          <tr>
            <td class="hotName"></td>
            <td class="hotDesc">&nbsp;</td>
            <td class="hotMenu"></td>
          </tr>
        </table>
    </div> 

    <div id="HasCart_JamstoneInn">
     <table width="380px" border="1" cellspacing="3" cellpadding="0">
          <tr>
            <td class="hotName"></td>
            <td class="hotDesc">&nbsp;</td>
            <td class="hotMenu"></td>
          </tr>
        </table>
    </div>    



<h2>Something Like This</h2>

    <select name="price">
        <option value="980.00">Single Room (980.00)</option>
        <option value="1,300.00">Deluxe Room (1,300.00)</option>
        <option value="1,600.00">Twin Room (1,600.00)</option>

        <option value="1,500.00">Matrimonial Room (1,500.00)</option>
        <option value="1,800.00">Presidential Suites (1,800.00)</option>
        <option value="300.00">Extra Bed (300.00)</option>   
        <option value="150.00">Free Breakfast (150.00)</option>    
        <option value="200.00">Extra Person (200.00)</option>          
    </select>



</body>
</html>

1 Ответ

0 голосов
/ 17 сентября 2009

Вы на правильном пути, лучше всего настроить параметры в вашей функции HotelQuery. Здесь мы используем самозавершающийся оператор while (оптимизированный для оператора for) и соединение с массивом - это быстрее и, возможно, чище, чем конкатенация строк. Дайте знать, если у вас появятся вопросы. Всего наилучшего, М

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js">
</script>
<script type="text/javascript" charset="utf-8">
    $(function(){

        function buildPriceOptions(rate,type)
        {
            var i = rate.length, a = [];
            while(i--) a.push(
                [
                    '<option value="',rate[i],'">',type[i],
                    ' (',rate[i],')','</option>'
                ]
                .join('')
            );
            return a.reverse().join('\n')
        }

        function HotelQuery()
        {
            switch (true) {
                case true : 
                    var strHotelName = 'Jamstone Inn';
                    var strHotelDesc = 'Hotel Description Jamstone Inn';

                    var strHotelRate = [
                        '980.00', '1,300.00', '1,600.00',
                        '1,500.00', '1,800.00', '300.00',
                        '150.00', '200.00'];

                    var strHotelRoomType = [
                        'Single Room', 'Delux Room','Twin Room',
                        'Matrimonial Room', 'Presidential Suites', 'Extra Bed',
                        'Free Breakfast', 'Extra Person'];    

                    var htmPrice = buildPriceOptions(
                        strHotelRate,
                        strHotelRoomType
                        );
                break;
            }
            return {
                name     : strHotelName,
                desc     : strHotelDesc,
                rate     : strHotelRate,
                roomType : strHotelRoomType,
                prices   : htmPrice
            }; 
        };
        hotel = HotelQuery();
        $('#HasCart_TetrisHotel .hotMenu').append(
            [ 
                '<select name="price">',
                hotel.prices,
                '</select>'
            ]
            .join('')
        );
    })
</script>
</head>
<body>
    <div id="HasCart_TetrisHotel">
        <div class="hotMenu">

        </div>
    </div>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...