简体   繁体   English

将JS函数的url返回值传递给href

[英]Pass a url return from JS function into href

I'm still new to JS and HTML5 我还是JS和HTML5的新手

So I have a URL that I store in a var 所以我有一个URL,我存储在var中

var Base_URL = "https://www.mywebsite.com/info?username";

Which is linked to a Database that has access to a username value that can contain spaces. 链接到有权访问可以包含空格的用户名值的数据库。

I parse this url into a function 我将此网址解析为一个函数

function removeSpaceURL(url) {
var update = url.split(' ').join('%20');
return update;
}

It is not the best way I know but it works good enough for its purpose. 这不是我所知道的最好方法,但足以达到目的。

Where I'm stuck is that I want to return the update into a href reference so I can click it. 卡住的地方是我想将更新返回到href引用中,以便单击它。

    <p><a href="" onclick="removeSpaceURL(BASE_URL);return false;" >Survey</a></p> 
<script>
   var Base_URL = "https://www.mywebsite.com/info?username";

function removeSpaceURL(url) {
    var update = url.split(' ').join('%20');
    return update;}

</script>

When I try it on JSfiddle, I get the following error: 当我在JSfiddle上尝试时,出现以下错误:

{"error": "Please use POST request"} {“错误”:“请使用POST请求”}

The correct thing is to have Base_URL be a correctly-formed URL in the first place, which it isn't if there's a space in the username part of it. 正确的做法是首先将Base_URL设置为格式正确的URL,如果用户名部分中没有空格,则不是这样。

But assuming you're stuck with it, it's quite simple to set an attribute on an element: 但是假设您坚持使用它,那么在元素上设置属性非常简单:

<p><a id="target-link" href="">Survey</a></p> 
<script>
   var Base_URL = "https://www.mywebsite.com/info?username";
   document.getElementById("target-link").setAttribute(
        "href", encodeURI(Base_URL)
   );
</script>

Note using encodeURI as suggested by emiliopedrollo rather than a simplistic replacement of just spaces. 请注意,使用emiliopedrollo 建议encodeURI ,而不是简单地替换空格。 But that said, if parts of the URI have already been encoded correctly and only the username is the problem, encodeURI might double-encode things. 话虽如此,如果URI的部分已经被正确编码,只有用户名的问题, encodeURI可能会增加一倍编码的东西。 So if you just want to replace spaces: 因此,如果您只想替换空格:

document.getElementById("target-link").setAttribute(
    "href", Base_URL.replace(/ /g, "%20");
);

Also note that return false from an onclick on a a element will prevent the link from being followed, so I've left off the onclick entirely. 还要注意, return falseonclick一个上a元素会阻止跟着链接,所以我离开了onclick完全。

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

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