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

如何根据文本输入框的值动态设置form的action属性以在iframe打开链接

原有代码的核心错误

  • 页面元素全部放在</body>闭合标签之外,浏览器无法正常识别渲染
  • HTML属性无法直接读取JavaScript变量/表达式,你写的action=chart4.value只会被识别为固定字符串,不会实时读取输入框的值
  • 多个<form>标签未正确单独闭合,存在嵌套错误,表单逻辑完全失效

解决方案

最简洁的实现方式是给按钮绑定点击事件,点击时直接读取对应输入框的值,赋值给目标iframe的src即可,不需要额外用form提交逻辑。

修改后的完整可运行代码如下:

<html>
<head>
<script language="JavaScript">
function refreshIt() {
   if (!document.images) return;
   document.images['Gráfico1'].src = document.getElementById('chart1').value;
   document.images['Gráfico2'].src = document.getElementById('chart2').value;
   document.images['Gráfico3'].src = document.getElementById('chart3').value;
   setTimeout(refreshIt,500);
}
// iframe跳转逻辑
function loadIframe(chartId, iframeName) {
  const inputVal = document.getElementById(chartId).value.trim();
  if (inputVal) {
    document.querySelector(`iframe[name="${iframeName}"]`).src = inputVal;
  }
}
</script>
</head>
<body onLoad="setTimeout(refreshIt,500)">
<input type="text" id="chart1" name="chart1"><br>
<input type="text" id="chart2" name="chart2"><br>
<input type="text" id="chart3" name="chart3"><br>
<input type="text" id="chart4" name="chart4"><br>
<input type="text" id="chart5" name="chart5"><br>
<input type="text" id="chart6" name="chart6"><br>
<p></p>
<button type="button" onclick="loadIframe('chart4', 'iframe1')">I Frame 1</button>
<button type="button" onclick="loadIframe('chart5', 'iframe2')">I Frame 2</button>
<button type="button" onclick="loadIframe('chart6', 'iframe3')">I Frame 3</button>

<iframe name="iframe1" width="350" height="282"></iframe>
<iframe name="iframe2" width="350" height="282"></iframe>
<iframe name="iframe3" width="350" height="282"></iframe>
<p></p>
<img src="https://logospng.org/download/betfair/logo-betfair-fundo-laranja-1024.png" name="Gráfico1">
<img src="https://logospng.org/download/betfair/logo-betfair-fundo-laranja-1024.png" name="Gráfico2">
<img src="https://logospng.org/download/betfair/logo-betfair-fundo-laranja-1024.png" name="Gráfico3">
</body>
</html>

如果一定要保留form提交的实现方式,可以给每个form绑定submit事件,提交前动态修改action属性值即可,上述直接修改iframe src的方案代码更精简,无多余请求流程。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 04:06:02