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
.
像这样:
$(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)
这是我为原生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/