【问题标题】:use js functions return value for html form action attribute使用 js 函数返回值作为 html 表单动作属性
【发布时间】:2014-09-20 21:29:52
【问题描述】:

我想使用 JS 函数的返回值作为表单获取操作的 URL。是否有可能或者我需要在 onSubmit 属性中使用函数调用来设置表单属性?

编辑:这基本上是我想要做的

<div class="search">
    <form method="get" action="https://duckduckgo.com/" id="search-form">
        <input id="searchbar" type="text" name="q" size="31" maxlength="255" value="" autofocus="autofocus"/>
    </form>
    <script type="text/javascript">
        document.getElementById("search-form").action = "bang()";
    </script>
</div>

bang 函数是 JS 中 DDG 的 bang 系统的实现,所以我可以轻松地将 bang 添加到我网页中的搜索框。

【问题讨论】:

  • 您的意思是您有一个返回 URL 的 javascript 函数,并且在执行其他操作的过程中,您想调用该函数并设置表单的 action 属性?
  • form.action = yourFunction(); 会做到的。
  • 我想在用户提交表单时调用该函数,并评估该函数并将其返回的 url 用于获取请求

标签: javascript html get


【解决方案1】:

您可以使用表单的onsubmit 事件在实际提交发生之前设置操作。

<form id="testForm" methods="get" action="#" onsubmit="setFormUrl()">
    Search: <input type="text" name="q" />
    <input type="submit" value="Go" />
</form>
function bang()
{
    return "http://www.google.com";
}

function setFormUrl()
{
    var url = bang();
    document.getElementById('testForm').setAttribute('action', url);
}

【讨论】:

  • 是的,这是我的替代计划,但我想知道是否有任何方法可以在获取请求之前评估 action 属性中指定的函数,而不是浏览器尝试加载由函数生成的页面。
猜你喜欢
  • 2013-11-09
  • 2017-06-06
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 2019-10-07
  • 1970-01-01
  • 2017-07-14
相关资源
最近更新 更多