如何通过JavaScript设置表单操作?

我有一个HTML表单,该表单的操作应通过JavaScript动态设置。我该怎么做?这是我要实现的目标:


<script type="text/javascript">

function get_action() { // inside script tags

 return form_action;

 }

</script>


<form action=get_action()>

...

</form>


慕哥9229398
浏览 484回答 3
3回答

慕斯709654

您不能以以外的标准HTML属性调用JavaScript函数onXXX。只需在窗口加载时分配它即可。<script type="text/javascript">&nbsp; &nbsp; window.onload = function() {&nbsp; &nbsp; &nbsp; &nbsp; document.myform.action = get_action();&nbsp; &nbsp; }&nbsp; &nbsp; function get_action() {&nbsp; &nbsp; &nbsp; &nbsp; return form_action;&nbsp; &nbsp; }</script><form name="myform">&nbsp; &nbsp; ...</form>您会看到我已经给了形式a name,以便可以在中轻松访问document。另外,您也可以在submit活动期间进行:<script type="text/javascript">&nbsp; &nbsp; function get_action(form) {&nbsp; &nbsp; &nbsp; &nbsp; form.action = form_action;&nbsp; &nbsp; }</script><form onsubmit="get_action(this);">&nbsp; &nbsp; ...</form>

幕布斯6054654

纯JavaScript:document.getElementById('form_id').action; //Will retrieve itdocument.getElementById('form_id').action = "script.php"; //Will set it使用jQuery ...$("#form_id").attr("action"); //Will retrieve it$("#form_id").attr("action", "/script.php"); //Will set it

蛊毒传说

实际上,当我们需要此操作时,我们希望根据所按下的提交按钮来更改操作。在这里,您甚至不需要分配name或分配id表单。只需使用formclicked元素的属性即可:<form action = "/default/page" >&nbsp; &nbsp; <input type=submit onclick='this.form.action="/this/page";' value="Save">&nbsp; &nbsp; <input type=submit onclick='this.form.action="/that/page";' value="Cancel"></form>
打开App,查看更多内容
随时随地看视频慕课网APP