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

使用Javascript与Flask实现点击按钮显隐图片功能失效求助

你代码的核心问题是误用了CSS display 属性的合法取值,display 不存在 show、hide 这两个属性值。你控制台逻辑运行正常是因为判断分支没有问题,只是给display赋的非法值被浏览器忽略了,所以显隐没有生效。

合法对应规则:

  • 元素隐藏:display 取值为 none
  • 元素显示:img属于行内块元素,display 取值为 inline-block 即可,也可以根据布局需求替换为 block

修正后HTML代码

<input type="text" class="rounded" name="fname" id="stock_check">
<img id="my_image" style="display: none;" src="{{url_for('static', filename='download.png')}}" alt="greencheck" width="25" height="25"/>

<button onclick="myFunction()">Click Me</button>

修正后Javascript代码

function myFunction() {
  var x = document.getElementById("stock_check").value;
  // 提前获取图片元素,避免重复查询DOM
  var targetImg = document.getElementById('my_image');
  if (x === 'W'){
    targetImg.style.display = 'inline-block';
    console.log('if_state');
    console.log(x);
  } else {
    targetImg.style.display = 'none';
    console.log('else_state');
    console.log(x);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 05:45:02