0
Why am I getting reference error for "loadByBreed" function ?
I am getting uncaught reference error saying loadByBreed is not defined https://code.sololearn.com/Wy66yLVlxQq4/?ref=app
6 odpowiedzi
+ 2
because function scope: what is declared inside a function cannot be accessed from outside ;)
+ 2
its better practice to not polute global space ;)
to avoid "export" your function in global space, you need to avoid inlining event handler in html source, by getting the element reference and using addEventListener on it to attach your function: this way, you don't need to have it accessible in global space...
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
as well, it's better to use createElement to build your html tree and append it to target element rather than using innerHTML...
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
example:
function createBreedList(breedList) {
var k = Object.keys(breedList);
var s = document.createElement('select');
s.addEventListener('change',loadByBreed);
s.append(...k.map(breed => {
var o = document.createElement('option');
o.textContent = breed;
return o;
}));
var b = document.querySelector("#breed");
b.textContent = ''; // clear content
b.append(s);
}
+ 1
because loadByBreed is not defined... in global scope ^^
to "export" the function to global scope, either declare it outside of onload event handler, or put inside it:
window.loadByBreed = loadByBreed;
0
Thank you so much man it worked 😘 but I didn't understand why we need to do that
Could you please explain?
0
I used onload because dom was not working.The reason was that js was not loading after html as I read somewhere that sololearn put script tag in the head section so I thought I have to declare all the functions inside of onload
By the way thanks again
0
You really know well