Access a document.ready variable from outside it

1

Good, I have a variable nombre within document.ready that I want to access from outside document.ready but I can not. If I declare the variable outside the document.ready , when I assign a value within the document.ready , it is lost when I exit.

I have read that if you declare the variable from outside the function, it becomes global and can be accessed from the whole document but something I am doing wrong.

I put the name variable as an example.

        $(document).ready(function(){
         url = new URL(location.href); //Mediante esta propiedad accedemos a la dirección URL completa de la página mostrada en una ventana
            datos = JSON.parse(url.searchParams.get('objJson')); //Hacemos el proeso inverso, convertimos el string enviado a objeto Json
                //La propiedad searchParams de la interfaz URL devuelve un objeto URLSearchParams que permite el acceso a los argumentos de consulta GET contenidos en la URL.
                for(var i = 0; i < datos.length; i++){
                    //alert(datos[i].api_key);
                }
            nombre="adios";

            }); 

        alert(nombre);
    
asked by Lorenzo Martín 21.09.2017 в 10:59
source

2 answers

1

I think you're messing around a bit. The problem with your code is not that you can not access the variable nombre from outside the function defined in the $(document).ready method, but that when you access the variable nombre has not yet been initialized so no It has no value.

If you use a variable without declaring it previously with a var javascript statement generate a variable in the global context that can automatically be accessed from anywhere in your code. This is not a good practice but it works. If you want to define a global variable, it is preferable that you expressly declare it in this context.

In your code the problem is that the $(document).ready function does not run until the page loads, while alert(nombre); executes immediately as the code is interpreted with what is executed before that no value has been assigned to the variable.

If you create, outside the context of $(document).ready , a function that accesses the name value and execute it after the code that initializes the variable has been executed, you will see that you can access its content without problems.

Look at this example. The first console.log will show the value undefined because it is executed before the variable is initialized. The function% mostrarNombre will show the value of the variable once initialized:

// Declaración global para que sea accesible desde todo el código
var nombre;

// Código que se ejecuta una vez que se haya finalizado la carga de la página
$(document).ready(function(){
  var url = new URL(location.href);
  var datos = JSON.parse(url.searchParams.get('objJson'));

  // .....
  
  // Inicializamos la variable
  nombre="adios";
  
  // Una vez inicializado llamamos a mostrarNombre
  mostrarNombre();
}); 

// Este código se ejecuta antes de finalizar la carga de la página por lo que nombre es 'undefined'
console.log('Valor antes de inicializar: ' + nombre);

// Función que muestra el valor de nombre
function mostrarNombre(){
  console.log('Valor desde mostrarNombre: ' + nombre);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 21.09.2017 / 11:53
source
4

Yes, in general, if you want a variable to be accessible for several functions, you must declare it in the context where those functions are declared.

But I do not understand why you want it out of $(document).ready(function () {...} , the normal and desirable thing is that all your code is within that function:

let miVariable='antes'
$(function () { //jQuery aconseja esto en lugar de $(document).ready(...
  miVariable='despues';
});
alert(miVariable)  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

As you can see, the variable has the value 'before', because the alert will be executed before the code waiting for the document to be ready.

    
answered by 21.09.2017 в 11:11