[英]Add Query-String parameter to static link on click
I'm looking for a robust way of dynamically injecting a query string parameter when a visitor clicks on a static anchor-link. 我正在寻找一种在访问者点击静态锚链接时动态注入查询字符串参数的强大方法。
For example a link: 例如一个链接:
<a href="http://www.johndoeslink.com">Test</a>
I want to pass a query string to the next page but have to assign the value dynamically. 我想将查询字符串传递给下一页但必须动态分配值。 How can I achieve this?
我怎样才能做到这一点?
I know this is simple I'm just missing something obvious! 我知道这很简单,我只是遗漏了一些明显的东西! =\\
= \\
Thanks in advance, 提前致谢,
John d 约翰d
There are many ways you could do this. 有很多方法可以做到这一点。 Below I've listed two very simple methods.
下面我列出了两种非常简单的方法。 Here I'm assuming you already have a reference to your
a
element (here I've called this element
): 在这里我假设你已经有了一个参考的
a
元素(在这里我已经叫这个element
):
href
attribute href
属性 element.href += '?query=value';
element.addEventListener('click', function(event) {
// Stop the link from redirecting
event.preventDefault();
// Redirect instead with JavaScript
window.location.href = element.href + '?query=value';
}, false);
If you already know the value to append when loading the page then you can add this when the document is ready : If you're using JQuery use this: 如果您已经知道在加载页面时要追加的值,那么您可以在文档准备就绪时添加它:如果您正在使用JQuery,请使用以下命令:
$( 'class' ).attr( 'href', function(index, value) {
return value + '?item=myValue';
});
Otherwise (plain Javascript): 否则(普通Javascript):
var link = document.getElementById("mylink");
link.setAttribute('href', 'http://www.johndoeslink.com'+'?item=myValue');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.