[英]How to form dynamic link in JavaScript?
I would like to form a link on the client end. 我想在客户端上形成一个链接。
I think that need to be urlencoded but I am pretty confused with this. 我认为这需要进行urlencode,但是对此我感到很困惑。 Is this right?
这是正确的吗?
var link = document.createElement("a");
//addParams function just replaces the 0th and 1th occurrence with values
a.link = url.addParams(valueO, value1); // url is /home/testpage.aspx?{0}={1}
I think you should do link.href = escape("<your url>");
我认为您应该做
link.href = escape("<your url>");
plus you need to add some innerHTML - link.innerHTML = 'Click Here';
另外,您需要添加一些innerHTML-
link.innerHTML = 'Click Here';
...and then finally add it into the page at some point. ...然后最终将其添加到页面中。
Shouldn't that be link.href = url.addParams(valueO, value1);
不应该是
link.href = url.addParams(valueO, value1);
? ?
And both value0
and value1
should be sent (individually) through either escape()
or encodeURIComponent()
( I believe the latter is recommended over escape()
). 而且
value0
和value1
都应(分别)通过escape()
或encodeURIComponent()
( 我认为,建议使用后者而不是escape()
)。 You probably will want to do this in addParams()
before you replace {0}
and {1}
in your URL string. 在替换URL字符串中的
{0}
和{1}
之前,您可能希望在addParams()
执行此操作。
You could also do something like addParams(encodeURIComponent(value0), encodeURIComponent(value1))
but in my opinion, that's asking for trouble if you forget to encode some values in a call somewhere. 您还可以执行类似
addParams(encodeURIComponent(value0), encodeURIComponent(value1))
但是在我看来,如果您忘记在某个地方的调用中对某些值进行编码,那就麻烦了。 It'd be better to move the encoding into the function itself. 最好将编码移入函数本身。
Here's an explanation of what escape(), encodeURI(), encodeURIComponent()
do and how they're different and when to use each . 这是对
escape(), encodeURI(), encodeURIComponent()
作用以及它们之间的区别以及何时使用它们的解释 。
var link = document.createElement('a');
var href = document.createAttribute('href');
link.setAttribute(href,'http://www.example.com?'+paramKey+'='+paramValue);
link.innerText ="Go here";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.