我正在寻找一种强大的方法,在访问者单击静态锚链接时动态注入查询字符串参数。
例如,一个链接:
<a href="http://www.johndoeslink.com">Test</a>
我想将查询字符串传递到下一页,但必须动态地分配值。我该如何实现?
我知道这很简单,只是我错过了什么明显的东西! =\
提前感谢,
John d
我正在寻找一种强大的方法,在访问者单击静态锚链接时动态注入查询字符串参数。
例如,一个链接:
<a href="http://www.johndoeslink.com">Test</a>
我想将查询字符串传递到下一页,但必须动态地分配值。我该如何实现?
我知道这很简单,只是我错过了什么明显的东西! =\
提前感谢,
John d
有许多方法可以做到这一点。以下是我列出的两种非常简单的方法。在这里,我假设您已经有了对元素的引用(这里我称之为element
):
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);
$( 'class' ).attr( 'href', function(index, value) {
return value + '?item=myValue';
});
var link = document.getElementById("mylink");
link.setAttribute('href', 'http://www.johndoeslink.com'+'?item=myValue');
if
语句来检查是否已经存在一个window.location.search
。如果存在,就可以使用下面的代码将目标 URL 设置为element.href + '&query=value'
:if (window.location.search) { window.location.href = element.href + '&query=value'; }
- James Donnellyelement.search = '?query=value'
。这样,您就不必费心去处理元素是否已经有查询字符串,而是可能会添加到其中而不是替换它。 - ErikE