首页 > 解决方案 > 按钮点击结果:HTML中的“'功能'未定义”

问题描述

我正在使用 CodeSandbox 为我的社交媒体编写本地化访问点(只是为了玩他们拥有的 Vanilla 包裹包)。现在,我的按钮调用了单独的函数,但是当我选择一个按钮时,错误“Function未定义”

我的按钮函数存储在与常规 JavaScript 不同的文件中。

我查看了 W3Schools 以了解这是如何完成的。有几次我什至尝试将函数放在 HTML 页面本身中,看看是否有帮助;但是,错误仍然出现。

下面是一个 HTML 示例:


<button type="button" onclick="sShowFunction()">
          Discord Status
        </button>
        <br />
        <p id="dshow">Reveal Discord Status</p>
        <script src="extras/buttons.js" type="text/javascript"></script>

这是js函数:


function sShowFunction() {
  document.getElementById("dshow").innerHTML = `
  <iframe src="https://discordapp.com/widget?id=<server id>&theme=dark" width="350" height="500" allowtransparency="true" frameborder="0"></iframe>
  `;
}

当我按下按钮显示不和谐小部件时,我期望输出。相反,我产生了上述错误。我最好的猜测是我缺少一段代码来调用该函数。在控制台中,我收到此错误: sShowFunction' is defined but never used. (no-unused-vars)

标签: javascripthtmlfunctiononclickcodesandbox

解决方案


取决于你在哪里声明了函数..可能是不可访问的..从 html 级别

确保您的 js 代码位于有效的脚本标记内

<script>
  function sShowFunction() {
     document.getElementById("dshow").innerHTML = '
       <iframe src="https://discordapp.com/widget?id=<server id>&theme=dark" 
     width="350" height="500" allowtransparency="true" frameborder="0"></iframe>
  ';
  }
</script>

并且不要使用 backtics 来换行字符串 .. 使用引号


推荐阅读