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

JavaScript在JSBin、CodePen可用,正式网站失效求排查

代码无法在正式网站运行的问题分析及修复

核心问题

  • 脚本类型声明错误:HTML中<script>标签的type属性值写为JavaScript,标准MIME类型应为text/javascript(HTML5中可省略该属性),部分浏览器会因类型不识别而不执行脚本。
  • DOM未就绪就执行绑定:事件绑定代码直接写在head的脚本中,此时页面DOM元素尚未加载完成,$('select[name]')无法匹配到任何select元素,导致change事件绑定失效。

修复后的代码

JavaScript部分

$(document).ready(function() {
  $('select[name]').change(function(){
    var txt = "Txt", 
        selectName = this.name,
        inputName = selectName.concat(txt);
    document.getElementById(inputName).value = this.value;
  });
});

HTML部分(修正脚本标签)

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Testing</title>  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
    
    <script type="text/javascript">
      // 上述修复后的JS代码放在此处
    </script>
  </head>

  <body>
    <button id="copy">copy</button>
    <form id="form1">
      <select id="selecter123" name="selecter123" size="5" style="width: 400px;">
        <option value="01">001</option>
        <option value="02">002</option>
        <option value="03">003</option>
        <option value="04">004</option>
      </select>
      <input id="selecter123Txt" name="selecter123Txt" type=text>
    </form>

    <br><br><br>
    
    <form id="form3">
      <select id="selecter456" name="selecter456" size="5" style="width: 400px;">
        <option value="01">001</option>
        <option value="02">002</option>
        <option value="03">003</option>
        <option value="04">004</option>
      </select>
    </form>
    <form id="selecter456Txt6">
      <input id="selecter456Txt" name="selecter456Txt" type=text>
    </form>
  </body> 
</html>

补充说明

JSBin、CodePen等在线工具默认会自动处理脚本执行时机(如将脚本放在DOM就绪后执行),因此在这些环境中代码能正常运行,但正式网站需要手动确保DOM加载完成后再执行元素操作。若使用HTML5文档模式,<script>标签的type属性可直接省略,浏览器会默认识别为text/javascript。

内容的提问来源于stack exchange,提问作者Callum

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:53:20