+ 1
Why does the following code gives an error saying p_1 is not defined
10 ответов
+ 1
Abhay Sorry. Did not notice because the code was full of commented out text.
It turned out that when you give an id to an element, it is added in JavaScript namespace. So that was why it was accessible.
See this
https://code.sololearn.com/WiJpHv50Zi1u/?ref=app
+ 1
Because the onload event fires after detect is created and variable p_1 can not be accessed outside the function
You have to pass p_1 as an argument to the function.
Like this
window.onload=function(){
var p_1=document.querySelector(".page1");
detect(p_1);
};
function detect(page){
.....use 'page' not 'p_1' here
}
0
CodeShow Hoisting is not the issue here. Even if you convert detect to an arrow function the problem still persists. Variables declared inside functions can not be accessed outside the functions no matter what
0
Ore I have this similar code and it works well ? Am i missing something!
https://code.sololearn.com/WHGX1dAI1cTm/?ref=app
0
Abhay In your code, the functions are declared within the event callback itself. So they have access to the variables declared within the callback.
Its like this
function () {
var a = 8;
//YES
function() {
//YES
}
}
//NO
The regions labelled YES can access the variable a. Those labelled NO can not.
0
Ore but it is like this:
function(){
}
function1(){
}
0
Thanks a lot :)