简体   繁体   English

如何使用javascript函数将网址返回表单操作

[英]How to return a url to form action using a javascript function

I want to return a url to form action using javascript function. 我想使用javascript function.返回一个网址以形成表单操作javascript function.

I am calling the function like this: 我正在这样调用函数:

<form action="javascript:getUrl()">

And my function is returning strings of url like this: 我的函数返回的是这样的url字符串:

function getUrl(){
    if(condition)
        return "this string url";
    else
        return "this string url";
}

When I am doing this, the resultant page simply shows the urls in text format on browser instead of loading them. 当我这样做时,结果页面仅在浏览器上以文本格式显示网址,而不是加载它们。

I am pretty new to these scripting and web designing stuffs. 我对这些脚本和Web设计方面的知识还很陌生。

javascript:getUrl() is not going to be interpreted as JS code, it's just a literally string. javascript:getUrl()不会被解释为JS代码,而只是字面上的字符串。

Instead select form element and set its action property: 而是选择表单元素并设置其action属性:

function getUrl() {
  // ...
}

document.querySelector('form').action = getUrl()

Naturally, use more specific selector for your form, id or class. 自然地,为您的表单,ID或类使用更具体的选择器。

You can use the id of your form to know the action url. 您可以使用表单的ID来了解操作网址。

Javascript : Javascript:

<script type="text/javascript">
function form_action() { 
  if (document.getElementById("myFormId").action == "url1.html"){
     // do something
  }
  if (document.getElementById("myFormId").action == "url1.html"){
     // do something else 
  }

  // ...
}
</script>

The html form : html形式:

<form action="yourUrl" onsubmit="this.action=form_action();" id="myFormId">
...
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM