使用jquery将参数添加到页面上的链接

Pri*_*iyo 18 javascript jquery

如何ajax=1使用jquery 添加让我们说出我页面上所有链接的内容.我还需要检查url是否有现有参数.例如http://example.com/index.php?pl=132必须成为http://example.com/index.php?pl=132&ajax=1

此外,如果链接没有任何参数,例如http://example.com/index.php,http://example.com/index.php?ajax=1我将要在文档就绪上加载jQuery脚本,以便在页面加载时更改所有链接.

Nic*_*ver 55

你可以这样做:

$(function() {
   $("a").attr('href', function(i, h) {
     return h + (h.indexOf('?') != -1 ? "&ajax=1" : "?ajax=1");
   });
});
Run Code Online (Sandbox Code Playgroud)

document.ready这看着每一个<a>,看看它的href,如果它?已经包含已附加,&ajax=1如果它没有,它附加?ajax=1.


SLa*_*aks 5

像这样:

$(function() {
    $('a[href]').attr('href', function(index, href) {
        var param = "key=value";

        if (href.charAt(href.length - 1) === '?') //Very unlikely
            return href + param;
        else if (href.indexOf('?') > 0)
            return href + '&' + param;
        else
            return href + '?' + param;
    });
})
Run Code Online (Sandbox Code Playgroud)


sea*_*ges 5

这是我为原生Javascript组合的解决方案,它支持现有的查询字符串和锚点:

function addToQueryString(url, key, value) {
    var query = url.indexOf('?');
    var anchor = url.indexOf('#');
    if (query == url.length - 1) {
        // Strip any ? on the end of the URL
        url = url.substring(0, query);
        query = -1;
    }
    return (anchor > 0 ? url.substring(0, anchor) : url)
         + (query > 0 ? "&" + key + "=" + value : "?" + key + "=" + value)
         + (anchor > 0 ? url.substring(anchor) : "");
}
Run Code Online (Sandbox Code Playgroud)

我在JSBin上发布了我现有的测试:http://jsbin.com/otapem/2/


Sam*_*son 2

如果您对插件感兴趣,可以使用 jQuery查询字符串对象。这将允许您简单地检查查询字符串中的参数,并在必要时添加更多、删除一些或编辑其他参数。

  • 这不是他要找的。 (3认同)