如何在 href 中插入 JavaScript 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28148155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:29:48  来源:igfitidea点击:

How to insert a JavaScript variable in href?

javajavascriptvariableshref

提问by Nika Kvezereli

I'm trying to put a JavaScript variable in the href.

我正在尝试将 JavaScript 变量放入href.

<a href="http://google.com/{$order.paymentBefore}/{$order.guid}">click here</a>

When I am using href, because I want the link to appear as "Click here", it stays in the link as it is --> {$order.paymentBefore}/{$order.guid}, unchanged.

当我使用 时href,因为我希望链接显示为“单击此处”,所以它保持原样 -->{$order.paymentBefore}/{$order.guid}不变。

回答by prog1011

Use click eventfor <a>as below

使用click event<a>如下

HTML

HTML

<a onclick="redirectTo();">click here</a>

JavaScript function

JavaScript 函数

function redirectTo(){
     var parameter1 = $order.paymentBefore; // some thing like this you can set value for 1st Param.
     var parameter2 = $order.guid; // some thing like this you can set value for 2nd Param.
    window.location.href="http://google.com/"+parameter1+"/"+parameter2;

}

回答by Vijaya

You can mention href value upto what static value you have and the variable can be given in onclick call. See below example:

您可以将 href 值提及到您拥有的静态值,并且可以在 onclick 调用中给出该变量。见下面的例子:

    var orderLink= "xyz";
     <a style="font-size:large;align-content:center" 
href="http://<static value>" onclick="location.href = this.href + orderLink; return false;"> Click Here </a>

回答by Anirudh Ajith

In your javascript, include a function that changes the href of to what you want. You cannot use it the way you have.

在您的 javascript 中,包含一个将 href 更改为您想要的内容的函数。你不能以你现有的方式使用它。

Let your html tag look something like this.

让你的 html 标签看起来像这样。

<a id="hyperlink" href="#">Click Here</a>

Now create a javascript function which updates the url whenever you call it.

现在创建一个 javascript 函数,它会在您调用它时更新 url。

function myFunction() { //Call this function whenever you want to update the href
    var link = document.getElementById("hyperlink");
    link.href = "http://google.com/" + $order.paymentBefore + "/" + $order.guid;
}