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

Node.js Pug模板元素显示值不更新?jQuery无法使用?

问题解答

关联代码示例

html
  head
    title abc123
  body
    for t in things
      button(onclick="doThing('" + t + "')") #{t}
      br
    div(id='box' style='display:none;')
      input(id='boxInput' type='text')
      button
    script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js' type='text/javascript')
    script(type='text/javascript').
      var doThing = function (thing) {
        document.getElementById('box').style.display = 'block';
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open('POST', '/doThing', false);
        xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xmlHttp.send('name=' + thing);
      }

1) 点击按钮后box元素不显示的原因分析

我帮你梳理几个最可能的触发点:

  • 同步请求阻塞UI渲染:你在代码里用了同步XMLHttpRequest(xmlHttp.open的第三个参数是false)。同步请求会完全占用浏览器主线程,包括DOM的重绘逻辑。也就是说,哪怕你先设置了box.style.display = 'block',浏览器也会被同步请求卡住,直到请求完成(或失败)才会更新界面。如果请求耗时久,用户就会觉得box根本没出现过。

  • 按钮点击事件的语法错误:看生成按钮的代码button(onclick="doThing('" + t + "')") #{t},如果things数组里的元素包含单引号(比如t的值是"it's a test"),最终生成的HTML会变成:

    <button onclick="doThing('it's a test')">it's a test</button>
    

    这会直接导致JavaScript语法报错,doThing函数根本不会执行,自然box不会被显示。

  • DOM元素获取异常:虽然概率较低,但可以在doThing函数开头加一句console.log(document.getElementById('box')),确认元素是否能被正常获取——如果返回null,说明ID拼写错误或者元素还没加载到DOM中。

修复建议

  • 把同步请求改成异步请求,避免阻塞UI:
    var doThing = function (thing) {
      document.getElementById('box').style.display = 'block';
      var xmlHttp = new XMLHttpRequest();
      xmlHttp.open('POST', '/doThing', true); // 改为异步
      xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      // 添加请求完成后的回调
      xmlHttp.onload = function() {
        if (this.status >= 200 && this.status < 400) {
          console.log('请求成功:', this.responseText);
        } else {
          console.log('请求失败');
        }
      };
      xmlHttp.send('name=' + thing);
    }
    
  • 避免字符串拼接生成事件,改用事件委托规避特殊字符问题:
    // 给按钮统一加类名和数据属性
    for t in things
      button(class='thing-btn' data-thing=#{t}) #{t}
      br
    
    // 在脚本里绑定事件
    document.addEventListener('DOMContentLoaded', function() {
      document.querySelectorAll('.thing-btn').forEach(btn => {
        btn.addEventListener('click', function() {
          var thing = this.dataset.thing;
          doThing(thing);
        });
      });
    });
    

2) $ is not defined的问题排查

这个错误说明jQuery没有被正确加载到页面中,常见原因和解决方法:

  • jQuery脚本加载失败:

    • 打开浏览器控制台的「网络」标签,查看jQuery的请求状态。如果是404或其他错误,可能是CDN地址有误(比如协议不匹配、版本号写错)。你可以换个稳定的CDN地址试试:
      script(src='https://code.jquery.com/jquery-3.3.1.min.js' type='text/javascript')
      
    • 可能是广告拦截器或安全插件阻止了CDN资源加载,暂时禁用插件后再测试。
  • 脚本加载顺序错误:
    即使你的代码里jQuery在自定义脚本之前,如果自定义脚本加了async/defer属性,或者模板渲染时意外把自定义脚本放到了jQuery之前,都会导致$未定义。确保依赖jQuery的代码在jQuery加载完成后执行,比如包裹在DOMContentLoaded事件里:

    document.addEventListener('DOMContentLoaded', function() {
      // 这里写依赖jQuery的代码
      $.ajax({
        type: 'POST',
        url: '/doThing',
        // 其他配置
      });
    });
    
  • $变量被覆盖或禁用:
    有些第三方库会覆盖$,或者你可能不小心调用了jQuery.noConflict(),导致$不再指向jQuery。这种情况下,可以直接用jQuery代替$:

    jQuery.ajax({
      type: 'POST',
      url: '/doThing',
      // 其他配置
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:45:14