2

我正在使用 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)

4

4 回答 4

0

取决于你在哪里声明了函数..可能是不可访问的..从 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 来换行字符串 .. 使用引号

于 2019-06-06T19:51:52.170 回答
0

为什么不在按钮中放置一个类/ID,然后像这样使用监听器:

<button type="button" id="sShowFunction">
          Discord Status
</button>
<br />
<p id="dshow">Reveal Discord Status</p>

<script>
document.getElementById("sShowFunction").onclick = function() {
    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>

此外,您可能会从 iframe 内部收到此错误。

您不能在开发人员控制台上发布一些错误照片或提供更多关于您的 JavaScript 的信息吗?

于 2019-06-06T19:58:37.530 回答
0

所以我们需要做的是在codesandbox上创建一个静态模板。为此,请转到左侧边栏上的设置选项,然后单击 create sandbox.config.json。然后在此,在模板下选择 ->静态选项,如下图所示。 在此处输入图像描述

为了节省时间,你可以分叉这个- https://codesandbox.io/s/static-vanilla-js-template-qzxfi

在这个 Github 问题上提到了一个详细的解决方案- https://github.com/codesandbox/codesandbox-client/issues/1502#issuecomment-584886419

于 2021-02-08T16:52:10.777 回答
0

查看 chrome>console>network request for buttons.js 是否正常(不是红色),因为您提供的代码在我的本地机器上工作

于 2019-06-06T20:02:20.790 回答