I create a function that should make my div visible on click. It works fine locally, but when I publish my project on Github pages I get an error " Uncaught ReferenceError: btnClick is not defined at HTMLElement.onclick ((index):51) ". Here's the script code:
document.getElementById('btn-share').onclick = function btnClick() {
let comma = document.getElementById('comm-share');
let tri = document.getElementById('trio');
if (comma.style.visibility === "hidden") {
comma.style.visibility = 'visible';
tri.style.visibility = 'visible';
}
else {
comma.style.visibility = 'hidden';
tri.style.visibility = 'hidden';
}
};
Image: HTML
What you are doing is assigning the.onclick while making another function called btnClick()
. There are a few ways to fix your code:
document.getElementById('btn-share').onclick = function () { let comma = document.getElementById('comm-share'); let tri = document.getElementById('trio'); if (comma.style.visibility === "hidden") { comma.style.visibility = 'visible'; tri.style.visibility = 'visible'; } else { comma.style.visibility = 'hidden'; tri.style.visibility = 'hidden'; } };
btnClick()
but just assigns a function to onclick
.
This would be the best choice if you wanted to call btnClick()
when you wanted to (well, you can do element.onclick).
function btnClick() { let comma = document.getElementById('comm-share'); let tri = document.getElementById('trio'); if (comma.style.visibility === "hidden") { comma.style.visibility = 'visible'; tri.style.visibility = 'visible'; } else { comma.style.visibility = 'hidden'; tri.style.visibility = 'hidden'; } }; document.getElementById('btn-share').onclick = btnClick;
The above assigns it to the function.
document.getElementById('btn-share').addEventListener("click", function() { let comma = document.getElementById('comm-share'); let tri = document.getElementById('trio'); if (comma.style.visibility === "hidden") { comma.style.visibility = 'visible'; tri.style.visibility = 'visible'; } else { comma.style.visibility = 'hidden'; tri.style.visibility = 'hidden'; } });
And the last one uses the .addEventListener()
function to assign the function to the onclick
.
It's your choice what you want to use.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.