简体   繁体   English

Javascript function 发布到 Github 时未定义

[英]Javascript function not defined when published to Github

I create a function that should make my div visible on click.我创建了一个 function 应该使我的 div 在点击时可见。 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) ".它在本地运行良好,但是当我在 Github 页面上发布我的项目时,出现错误“未捕获的ReferenceError:btnClick 未在 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图片: HTML

What you are doing is assigning the.onclick while making another function called btnClick() .您正在做的是分配 .onclick ,同时制作另一个名为btnClick()的 function 。 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'; } };
This doesn't make any btnClick() but just assigns a function to onclick . 这不会产生任何btnClick() ,而只是将 function 分配给onclick This would be the best choice if you wanted to call btnClick() when you wanted to (well, you can do element.onclick). 如果您想在需要时调用btnClick() ,这将是最佳选择(好吧,您可以使用 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.上面将其分配给 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 .最后一个使用 .addEventListener .addEventListener() function 将 function 分配给onclick

It's your choice what you want to use.你想用什么是你的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM