How to use a variable within another function?

Asked

Viewed 124 times

-2

I’m trying to prove a value by clicking a button. For this I need to fetch the value from a variable already created, but which is in another function. This is my code:

<script type="text/javascript">
//visualizar dados da linha da tabela ao carregar no botão
var tabela = document.getElementById("minhaTabela");
var linhas = tabela.getElementsByTagName("tr");

for(var i = 0; i < linhas.length; i++){
  var linha = linhas[i];
  linha.addEventListener("click", function(){
    //Adicionar ao atual
    selLinha(this, false); //Selecione apenas um
    //selLinha(this, true); //Selecione quantos quiser
  });
}


function selLinha(linha, multiplos){
  if(!multiplos){
    var linhas = linha.parentElement.getElementsByTagName("tr");
    for(var i = 0; i < linhas.length; i++){
      var linha_ = linhas[i];
      linha_.classList.remove("selecionado");    
    }
  }
  linha.classList.toggle("selecionado");
}

/**
Exemplo de como capturar os dados
**/
var btnVisualizar = document.getElementById("visualizarDados");

btnVisualizar.addEventListener("click", function(){
  var selecionados = tabela.getElementsByClassName("selecionado");
  //Verificar se eestá selecionado
  if(selecionados.length < 1){
    window.alert("Selecione pelo menos uma linha");
    return false;
  }
  
  var dados = "";

  for(var i = 0; i < selecionados.length; i++){
    var selecionado = selecionados[i];
    selecionado = selecionado.getElementsByTagName("td");
    dados += " - ID: " + selecionado[0].innerHTML +
            "\n"+ " - Designação: " + selecionado[1].innerHTML +
            "\n"+ " - Morada: " + selecionado[2].innerHTML +
            "\n"+ " - Estado: " + selecionado[4].innerHTML +
            "\n"+ " - Criado a: " + selecionado[5].innerHTML +
            "\n"+ " - Foto: " + selecionado[6].innerHTML + "\n";
  }
  
  window.alert(dados);
  return dados;
});

//botão resolvido
function cResolvido(){
   //var id = document.getElementById("btnResolvido").value;
  window.alert("Resolvido");
}

My goal is to show the variable dados in function cResolvido. Someone can help me?

3 answers

2


You can put the var dados = '' out of function so it becomes a global variable that has global scope : all scripts and functions on a web page can access it. And also whether you’re inside or outside the function, where you prefer to put it, you assign a value to the variable dados but not the declaration (declarations: var let const) just staying dados = '' (no matter where you are)

If you assign a value to a variable that has not been declared, it will automatically become a variable GLOBAL and so all scripts and functions on a web page can access it .

REMEMBERING CAUTION WHEN DOING THIS BECAUSE NO OTHER VARIABLE CAN GET THE NAME OF A GLOBAL VARIABLE, IN THE CASE I MENTIONED THERE THE VARIABLE dados AND SOME EXAMPLES OF YOUR CASE ARE THE VARIABLES linhas and btnVisualizar and tabela THAT YOU CALLED OUT OF OFFICE.

Instead of

var btnVisualizar = document.getElementById("visualizarDados");

btnVisualizar.addEventListener("click", function(){
  var selecionados = tabela.getElementsByClassName("selecionado");
  //Verificar se eestá selecionado
  if(selecionados.length < 1){
    window.alert("Selecione pelo menos uma linha");
    return false;
  }
  
  **var dados = "";**

 (...)

You can do :

Out of Office:

<script type="text/javascript">
//visualizar dados da linha da tabela ao carregar no botão
var tabela = document.getElementById("minhaTabela");
var linhas = tabela.getElementsByTagName("tr");
var dados = ''


(...)// funções e coisas

Anywhere without declaring the variable: (in this example in the same place you placed your var dados)

Test example (Execute him)

  var btnVisualizar = document.getElementById('visualizarDados')
    btnVisualizar.addEventListener("click", function(){

     dados = "";
     dados += 'TESTE'
     alert(dados)
     setTimeout(cResolvido,3000)//chamar função cResolvido depois de 3seg
     })
       //vou fechar a função para fazer o teste (buscar ele em outra função)
     function cResolvido() {
     alert(`cResolvido função pegar dados, dados é ${dados}`)
     }

      
      
<div id="visualizarDados">
    <p>Visualizar dados - teste (CLICK-ME)</p>
</div>

  • is working, thank you very much!!!

2

Well, the two simplest ways are:

1. Call, from within the original scope of the variable, the function you want by passing to variable inside as argument:

Call [nomeDaFunçãoQueRecebeAVariável](dados) from within the function [nomeDaFunçãoOriginal]().

2. Returning the variable to the global scope at the end of the function:

Declare:

[nomeDaFunçãoOriginal](){
   // ...
   dados = "";
   // ...
   return { dados };
 }

So to access this value from within another function, you call with:

[nomeDaFunçãoOriginal]().dados;

(or inserts this path into a local variable, to facilitate the writing the rest of the code, getting more organized)

1

You need the variable dados is a global variable. As you set the variable within a function, it will only work within that function.

  1. What is the scope of a variable?

When we refer to the variable scope we are referring to which location of our code a certain variable can be accessed. In Javascript there are only two types of scopes, which are they, scope global and local.

  1. Declaring variables in global scope

A global variable is defined when we declare a variable outside of any function, so it makes it accessible to any part of our application or website, which may be read and modified.

Source and examples here.

  • Good afternoon, I already corrected as you said, but I re-turn the value of the variable, and when I do window.Alert(data), data is null. how do I assign the value to data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.