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

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

问题描述

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

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

这是我要实现的目标:

<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天全站免登陆