单击时将Query-String参数添加到静态链接

kre*_*rex 7 html javascript html5 dom

我正在寻找一种在访问者点击静态锚链接时动态注入查询字符串参数的强大方法.

例如一个链接:

<a href="http://www.johndoeslink.com">Test</a>
Run Code Online (Sandbox Code Playgroud)

我想将查询字符串传递给下一页但必须动态分配值.我怎样才能做到这一点?

我知道这很简单,我只是遗漏了一些明显的东西!= \

提前致谢,

约翰d

Jam*_*lly 10

有很多方法可以做到这一点.下面我列出了两种非常简单的方法.在这里,我假设你已经有了对你的a元素的引用(这里我称之为element):

修改href属性

element.href += '?query=value';
Run Code Online (Sandbox Code Playgroud)

使用单击事件侦听器

element.addEventListener('click', function(event) {
    // Stop the link from redirecting
    event.preventDefault();

    // Redirect instead with JavaScript
    window.location.href = element.href + '?query=value';
}, false);
Run Code Online (Sandbox Code Playgroud)

  • @bperdue你可以使用`if`语句来检查`window.location.search`是否已经存在.`if(window.location.search)window.location.href = element.href +'&query = value';` (3认同)