Pregunta

Me gustaría saber si mi método es eficiente y correcta.mi código no funciona, aunque, no sé por qué.

<!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 HotelQuery(HotelName) {
   switch (HotelName) {
    case 'TimelessHotel': 
     var strHotelName = 'Timeless Hotel';
     var strHotelDesc = 'Hotel Description Timeless Hotel';
     var strHotelPrice = ['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 strHotelPrice = ['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 Paradise Inn

    case 'TetrisHotel': 
     var strHotelName = 'Tetris Hotel';
     var strHotelDesc = 'Hotel Description Tetris Hotel';
     var strHotelPrice = ['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 Tetris Hotel 

    case 'JamstoneInn': 
     var strHotelName = 'Jamstone Inn';
     var strHotelDesc = 'Hotel Description Jamstone Inn';
     var strHotelPrice = ['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 Jamstone Inn 

   }
  };


 });

   </script>     

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

<body>

  <a href="#" onclick="javascript: HotelQuery('TetrisHotel'); alert: (strHotelName, strHotelDesc, strHotelPrice);">Tetris Hotel Query</a>

</body>
</html>
¿Fue útil?

Solución

Su código no funciona porque las variables tienen un alcance de la función HotelQuery. Creo que lo que querrá hacer es devolver un objeto con propiedades de la función, y también usar el enfoque discreto de JavaScript para vincular un controlador de eventos de clic al elemento <a>.

Algo así

$(function() {
    $('a').click(function() {
        var hotel = HotelQuery('TetrisHotel');

        alert(hotel.name) // alerts 'Tetris Hotel'
    });
});

function HotelQuery(HotelName) {
    var strHotelName;
    var strHotelDesc;
    var strHotelPrice;
    var strHotelRoomType;

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

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

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

        case 'JamstoneInn': 
            strHotelName = 'Jamstone Inn';
            strHotelDesc = 'Hotel Description Jamstone Inn';
            strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00'];
            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,
        price: strHotelPrice,
        roomType: strHotelRoomType 
    }
};

Acabo de notar que también está devolviendo los mismos valores distintos del nombre y la descripción del hotel cada vez (puede que haya hecho esto solo como un ejemplo, no estoy seguro) . Puede asignar a todas las variables su valor en la declaración (o asignar los valores como propiedades del objeto devuelto), que no sean el nombre y la descripción del hotel, que puede asignar a partir del valor del argumento para el parámetro HotelName. Algo como

function hotelQuery(hotelName) {
    return {
        name: hotelName,
        desc: 'Hotel Desciption' + hotelName,
        // Keep prices as numbers and have a function to display them 
        // in the culture specific way. Numbers for prices will be easier to deal with
        price: [980, 1300, 1600, 1500, 1800, 300, 150, 200],
        roomType: ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person']
    } 
}

Otros consejos

Varios problemas.

1) no es necesario para la función a ser dentro de $(document).ready, deshacerse de eso.


2) Cada caso de declaración debe ser seguido por un break, no en solitario ;.Por ejemplo:

function HotelQuery(HotelName) {
    switch (HotelName) {
    case 'TetrisHotel': 
        // stuff goes here ...  
        break; //end Tetris Hotel 
    };
}

3) alert no debería ser seguido por un : en su onclick controlador:

alert: (strHotelName, strHotelDesc, strHotelPrice);

debe ser

alert(strHotelName, strHotelDesc, strHotelPrice);

También, alert sólo toma un parámetro, por lo que necesita para romper:

alert(strHotelName); alert(strHotelDesc); alert(strHotelPrice);

3) estás asumiendo strHotelName, strHotelDesc y strHotelPrice en el ámbito global, que no lo son.


En conjunto, es posible que desee probar algo como esto:

<!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">

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

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

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

    case 'JamstoneInn': 
     response.strHotelName = 'Jamstone Inn';
     response.strHotelDesc = 'Hotel Description Jamstone Inn';
     response.strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00'];
     response.strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person'];    
     break; //end Jamstone Inn 
   }

   return response;
  };

  $(document).ready(function() {
      var infoContainer = $('#hotel-information');
      $("#hotel-query").click(function() {
          var info = HotelQuery('TetrisHotel');
          infoContainer.text(info.strHotelName);
      });
  });
  </script>     

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

<body>
  <a href="#" id="hotel-query">Tetris Hotel Query</a>
  <p id="hotel-information"></p>
</body>
</html>
alert("myVar1= " + myVar1 +"/n"+ "myVar2= " + myVar2);

Colocar / n al lado de su cadena en un cuadro de alerta le permitirá mostrar varios vars con saltos de línea ingeniosos en un cuadro de alerta.

myVar1= Data
myVar2= more Data

Hay un par de cambios que haría.

Extraiga la función HotelQuery de la función ready.

En segundo lugar, todas esas variables estarán fuera de alcance cuando realice la llamada de alerta. Si desea que estén dentro del alcance, declare globalmente (fuera de su función) y configúrelos dentro de la función.

var name;

function doStuff() {
  name = "reggie";
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top