如何通过 JavaScript 设置表单操作? [英] How can I set the form action through JavaScript?

查看:23
本文介绍了如何通过 JavaScript 设置表单操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HTML 表单,它的操作应该通过 JavaScript 动态设置.我该怎么做?

I have an HTML form whose action should be set dynamically through JavaScript. How do I do it?

这是我想要实现的目标:

Here is what I am trying to achieve:

<script type="text/javascript">
    function get_action() { // Inside script tags
        return form_action;
    }
</script>

<form action=get_action()>
    ...
</form>

推荐答案

除了 onXXX 之外,您不能在标准 HTML 属性中调用 JavaScript 函数.只需在窗口加载期间分配它.

You cannot invoke JavaScript functions in standard HTML attributes other than onXXX. Just assign it during window onload.

<script type="text/javascript">
    window.onload = function() {
        document.myform.action = get_action();
    }

    function get_action() {
        return form_action;
    }
</script>

<form name="myform">
    ...
</form>

你看到我给了表单一个 name,这样它就可以在 document 中轻松访问.

You see that I've given the form a name, so that it's easily accessible in document.

或者,您也可以在 submit 事件期间进行:

Alternatively, you can also do it during submit event:

<script type="text/javascript">
    function get_action(form) {
        form.action = form_action;
    }
</script>

<form onsubmit="get_action(this);">
    ...
</form>

这篇关于如何通过 JavaScript 设置表单操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆