You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeSandbox中外部JavaScript文件无法运行问题求助

内嵌JS正常,移到单独文件后无法执行的解决方案

你的问题核心原因是:CodeSandbox默认将独立JS文件当作ES模块处理,模块内部定义的函数不会暴露到全局作用域,而HTML里的onclick="omg2(...)"是从全局作用域查找该函数,因此会出现找不到函数、点击按钮无反应的情况。

以下是两种可行的解决方案:

方案1:将函数挂载到全局window对象

修改script.js,把函数绑定到window对象上,让全局作用域可以访问:

window.omg2 = function(value, bgcolor, size = 40) {
  var textbox = document.getElementById('search_query');
  textbox.value = value + '; ' + 'size = ' + size ;
  textbox.style.backgroundColor = bgcolor;
  textbox.setAttribute('size', size);
}

HTML代码无需修改,保留原有的onclick属性即可。

方案2:改用事件监听(推荐,符合现代JS开发规范)

移除HTML中的onclick属性,通过JS代码绑定事件,避免依赖全局变量:

修改后的HTML:

<html>
  <head>
    <script src="./script.js"></script>
  </head>
  <body>
    <form name="hi" action="https://www.google.com/search">
      <input type="text" name="q" size="20" id="search_query" />
      <br /><br />
      <input type="button" value="OMG" />
      <input type="button" value="omg" />
      <input type="submit" value="google" />
    </form>
  </body>
</html>

修改后的script.js:

// 等待DOM加载完成后再执行代码
document.addEventListener('DOMContentLoaded', function() {
  // 获取页面元素
  const textbox = document.getElementById('search_query');
  const btnOmg = document.querySelector('input[value="OMG"]');
  const btnOmgLower = document.querySelector('input[value="omg"]');

  // 定义功能函数
  function omg2(value, bgcolor, size = 40) {
    textbox.value = `${value}; size = ${size}`;
    textbox.style.backgroundColor = bgcolor;
    textbox.setAttribute('size', size);
  }

  // 为按钮绑定点击事件
  btnOmg.addEventListener('click', () => omg2('thank you', 'goldenrod', 20));
  btnOmgLower.addEventListener('click', () => omg2('thanks', 'aquamarine'));
});

这个方案无需依赖全局变量,代码更模块化,同时也避免了DOM未加载完成时操作元素的潜在问题。

内容的提问来源于stack exchange,提问作者i-g

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:25:59