2010-11-24 10 views
5

¡Heredé un sitio web! que fue diseñado para funcionar en IE y solo IE parece ... Ahora me han pedido que haga que el sitio se ejecute en Firefox. He solucionado la mayoría de los errores sin ningún problema, pero este me tiene perplejo.setTimeout() no parece estar funcionando en Firefox?

setTimeout (fDelayedFunc, 1000);

Esta línea de Javascript, funciona bien en IE pero en Firefox la función fDelayedFunc nunca se dispara. Eliminé setTimeout y el contenedor de funciones e intenté ejecutar el código como parte de la función principal. Esto funciona sin ningún problema en absoluto.

Hay un montón de código involucrado, pero aquí está el principal, pero estoy teniendo problemas con. Si desea ver más del código, hágamelo saber.

  setTimeout(fDelayedFunc, 0); 

      //Save the current text box value 
      var vCurrentTBValue = vJQElement.val(); 

      function fDelayedFunc() { 

       if (vJQElement.val() == vCurrentTBValue) { 
        alert("test"); 

        //Get position list box should appear in 
        var vTop = vJQElement.position().top + 25; 
        var vLeft = vJQElement.position().left; 

        //Had to put a special case in for account due to the position co-ords being wrong. This is due to a css error 
        if (vHiddenFieldToWriteTo == "#ctl00_ContentPlaceHolder1_hfAccountCode") { 
         vTop = vJQElement.position().top + 58; 
         vLeft = vJQElement.position().left + 200; 
        } 
        else { 
         vTop = vJQElement.position().top + 25; 
         vLeft = vJQElement.position().left; 
        } 


        //Create div element 
        var vDivElement = $("<div id='divSearchBox' style='position:absolute; top:" + vTop + ";left:" + vLeft + "; z-index: 40000;'></div>"); 

        //Create list box 
        var vListBox = $("<select id='lbResults' tabIndex='" + vJQElement.attr("tabIndex") + "' size='4' style='height:400px;'></select>"); 


        //Bind a function to the list box which will select the item via either tab or enter 
        vListBox.bind("keydown", function() { 
         //Check if tab or enter has been pressed 
         if (event.keyCode == 9 || event.keyCode == 13) { 
          //Set hidden value to the selected items code 
          $(vHiddenFieldToWriteTo).val($(vListBox.find(":selected")).val()); 

          //Create postback 
          $('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click(); 
         } 
         //Check if the up arrow has been pressed at the top of the listbox 
         else if (event.keyCode == 38 && $(vListBox.find(":selected")).val() == $(vListBox.find(":first")).val()) { 
          //Focus back on the search box 
          vElement.focus(); 
         } 
        }).bind("dblclick", function() { 
         //Set hidden value to the selected items code 
         $(vHiddenFieldToWriteTo).val($(vListBox.find(":selected")).val()); 

         //Create postback 
         $('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click(); 
        }); 

        //Get search field 
        var vSearchText = vJQElement.val(); 

        var vDepotID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfDepotID").val(); 
        var vCustomerID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfCustomerID").val(); 
        var vCountryID = $("#ctl00_ContentPlaceHolder1_wizNewConsignment_hfCountryID").val(); 
        var vConsignee = vJQElement.attr("boolConsignee"); 

        //Set a loading image in place until call completed 
        vJQElement.css("backgroundImage", "url(images/small-loader.gif)"); 
        vJQElement.css("backgroundRepeat", "no-repeat"); 
        vJQElement.css("backgroundPosition", "right"); 





        //Make AJAX call 
        $.ajax({ 
         type: "POST", 
         contentType: "application/json; charset=utf-8", 
         url: "NewConsignment.asmx/fGetAddressesAndIDs", 
         data: "{'strSearchText' : '" + vSearchText + "', 'intDepotID' : '" + vDepotID + "', 'intCustomerID' : '" + vCustomerID + "', 'intCountryID' : '" + vCountryID + "', 'boolConsignee' : '" + vConsignee + "'}", 
         dataType: "json", 
         success: function fGetAddressesAndIDsResult(GetAddressesAndIDsResult) { 
          //Make sure there are results 
          if (GetAddressesAndIDsResult != null && GetAddressesAndIDsResult != "") { 
           var vNumberOfResults = 0; 
           var vNumberOfLearntAddresses = 0; 
           var vLearntAddressUniqueID = ""; 

           //Try to get results (first call will work on Linux and catch will work on Windows) 
           try { 
            //Check array exists (if this fails will go to catch) 
            if (GetAddressesAndIDsResult.d.length > 0) { 
             //Loop through the results 
             $.each(GetAddressesAndIDsResult.d, function() { 
              //Check for results 
              if (this.length > 0) { 
               //Evaluate JSON 
               var vAddress = eval("(" + this + ")"); 

               //Create list item 
               var vOption = $("<option class='AddressOption' value='" + vAddress.uniqueID + "'>" + vAddress.briefDescription + "</option>"); 

               //Find out number of learnt addresses 
               if (vAddress.uniqueID.indexOf("ConLA") != -1) { 
                vNumberOfLearntAddresses++; 
                vLearntAddressUniqueID = vAddress.uniqueID; 
               } 

               //Add list item to list box 
               vListBox.append(vOption); 

               //Mark result added 
               vNumberOfResults++; 
              } 
             }); 
            } 
           } 
           catch (err) { 
            //Loop through the results 
            $.each(GetAddressesAndIDsResult, function() { 
             //Check for results 
             if (this.length > 0) { 
              //Evaluate JSON 
              var vAddress = eval("(" + this + ")"); 

              //Create list item 
              var vOption = $("<option class='AddressOption' value='" + vAddress.uniqueID + "'>" + vAddress.briefDescription + "</option>"); 

              //Find out number of learnt addresses 
              if (vAddress.uniqueID.indexOf("ConLA") != -1) { 
               vNumberOfLearntAddresses++; 
               vLearntAddressUniqueID = vAddress.uniqueID; 
              } 

              //Add list item to list box 
              vListBox.append(vOption); 

              //Mark result added 
              vNumberOfResults++; 
             } 
            }); 
           } 

           //Check if only 1 learnt address was found 
           if (vNumberOfLearntAddresses == 1) { 
            //Auto select this address 
            //Set hidden value to the selected items code 
            $(vHiddenFieldToWriteTo).val(vLearntAddressUniqueID); 

            //Create postback 
            $('#ctl00_ContentPlaceHolder1_wizNewConsignment_btnRefresh').click(); 
           } 

           //Add list box to div 
           vDivElement.append(vListBox); 

           //Check if any results exist in div 
           if (vNumberOfResults != 0) { 
            //Append div to page 
            $("body").append(vDivElement); 

            //Auto select first item 
            vListBox.find(".AddressOption:first").attr("selected", "true"); 
           } 
          } 

          //Hide loading image 
          vJQElement.css("backgroundImage", "none"); 
         }, 
         error: function(XMLHttpRequest, textStatus, errorThrown) { 
          //Inform user of error 
          alert("An error occured, please try again"); 

          //Hide loading image 
          vJQElement.css("backgroundImage", "none"); 
         } 
        }); 
       } 

      } 
+2

¿Ha puesto llamadas 'console.log()' en la función? ¿Cómo sabes * que no funciona? ¡Te aseguro que 'setTimeout()' definitivamente funciona en Firefox! – Pointy

+1

Además, asegúrese de haber instalado Firebug antes de seguir adelante. – Pointy

+1

¿Está seguro de que la primera condición ('vJQElement.val() == vCurrentTBValue') se cumple cuando se dispara la función temporizada? –

Respuesta

3

Prueba esto:

setTimeout(function() { fDelayedFunc(); }, 0); 
+2

Eso realmente no es necesario. – xj9

+1

Esto realmente funcionó para mí ni idea por qué! ¡pero parece haber resuelto el problema! ¡gracias por la ayuda! – flyersun

+3

Por favor, explique. – Chris

-4

probar esto: setTimeout ('fDelayedFunc()', 0);

+3

No, eso realmente no va a hacer ninguna diferencia, además de que no es la forma correcta de hacer las cosas. El primer argumento debe ser una referencia de función, ya que en realidad está en el código. – Pointy

+2

No use cadenas como parámetro para 'setTimeout' y' setInterval'; no se recomienda usar esta sintaxis por las mismas razones que usar [eval()] (https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/eval#Don%27t_use_eval!). –

+0

'eval' es malo. – xj9

Cuestiones relacionadas