This question has already been answered:

Hello!

Tell me, please, why the variable created in the handler does not extend beyond its limits?

For example, here will not produce anything:

$('#search').on('keyup', function(){ a = 'test'; }); alert(a); //ничего не выведет 

And here it displays:

  $('#search').on('keyup', function(){ a = 'test'; alert(a); //окно test }); 

Reported as a duplicate by Dmitriy Simushev , aleksandr barakin , Streletz , user194374, zRrr Jun 30 '16 at 13:59 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • @Doofy I press the keys and apparently the handler that creates the variable should work. Then this variable outside the brackets should be known by the idea - Pavel
  • Asynchronous same! - Dmitriy Simushev
  • one
    @DmitriySimushev, then global between documents, and this one in the stream - Mr. Black
  • @Doofy, no difference. The deep reason is the misunderstanding of the asynchronous that is there, that is - Dmitriy Simushev

1 answer 1

When the button is pressed, only the handler function works, the code which is written after - worked after the handler was created.

a does not exist before pressing the button. Initially, an alert is displayed, and then we press any button in #search and alert with the output of a already swallowing flash

 $('#search').on('keyup', function() { a = 'test'; console.log(a); // test }); console.log(a); // a is not defined 

 $('#search').on('keyup', function() { a = this.value; f(a); }); function f(a) { console.log(a); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <input id='search'> 


You can declare a variable before the handler, assign a value to it in the handler, and then use it anywhere

 a = null; $('#search').on('keyup', function() { a = this.value; }); $('button').click(function() { console.log(a); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <input id='search'> <button>получить значение</button> 

  • I click on the keys and, in theory, the handler should work, which will create a variable. Then this variable outside the brackets should be cleared, but not displayed - Pavel
  • @Pavel, because when the button is pressed, only the handler functions work, the code that was written after - worked after the handler was created - Grundy
  • @Grundy, Cafe wording. Can I write in response? - Mr. Black
  • @Doofy And how to get this variable out of the function? - Pavel
  • @Pavel, no way :-) - Grundy