javascript - js 未捕获引用错误

标签 javascript

这个问题涉及到一些js在一个网站上可以工作,而在另一个网站上却不起作用。完全相同的代码。

此代码的目的是在移动设备上(或缩小浏览器窗口大小时)使顶部导航被 fa fa-bars 菜单取代。

它适用于 www.motorsport-tech.com。但是,它会在 www.skyforestinn.com 上生成“ Uncaught ReferenceError :myFunction 未定义”。

我将此脚本放置在紧邻正文标记之前:

<script>
    function myFunction() {
        var x = document.getElementById("navDemo");
        if (x.className.indexOf("w3-show") == -1) {
            x.className += " w3-show";
        } else {
            x.className = x.className.replace(" w3-show", "");
        }
    }

    // When user clicks anywhere outside of the modal, close it
    var modal = document.getElementById('ticketModal');
    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }
</script>

我在 html 中通过以下方式调用它:

onclick="myFunction()"

对 javascript 相当陌生,阅读大约 20 个对同一问题的回复并没有帮助,因为该代码在一个网站上有效,而在另一个网站上无效。很困惑。有人可以告诉我我做错了什么(除了不知道我一开始在做什么)或者指出我正确的方向吗?

最佳答案

这是您的脚本,逐字取自网站:

// Used to toggle the menu on small screens when clicking on the menu button        function myFunction() {         var x = document.getElementById("navDemo");         if (x.className.indexOf("w3-show") == -1) {             x.className += " w3-show";          } else {                x.className = x.className.replace(" w3-show", "");          }       }       // When the user clicks anywhere outside of the modal, close it     var modal = document.getElementById('ticketModal');     window.onclick = function(event) {        if (event.target == modal) {          modal.style.display = "none";         }     }

这是一行以注释开头的行,因此它绝对不执行任何操作。

正确格式化它,它应该按预期工作:

<script>
// Used to toggle the menu on small screens when clicking on the menu button
function myFunction() {
  var x = document.getElementById("navDemo");
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }
}
// When the user clicks anywhere outside of the modal, close it 
var modal = document.getElementById('ticketModal');
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>

此外,如果可能的话,我建议将脚本放在单独的文件中,以便将 HTML 与 JS 分开,并使编辑更容易,例如

<script src="myscript.js" defer></script>

然后,当您打开 myscript.js 时,类似这样的问题将更容易发现。

关于javascript - js 未捕获引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620970/

相关文章:

javascript - 访问 div 内的元素

javascript - 在空间和位置方面添加特定类

javascript - $window.focus() 不适用于 iOS Safari 中的现有选项卡

javascript - 无法将 JSON 从服务获取到 angularJs 路由中

JavaScript 内存泄漏

javascript - 如何在Nuxtjs中创建检查角色的中间件

javascript - Codeigniter 日期选择器不工作

javascript - 按钮可点击区域即使在按钮外也是可见的

javascript - Angular 4设置下拉列表中的选定选项

JavaScript 加载问题