如何在jquery中将变量附加到url?

Ste*_*ffi 7 url jquery attributes append href

如何在jquery中追加variable/text属性href

Dar*_*rov 12

你可以使用这个.attr()功能:

var foo = 'foo=bar';
$('a#foo').attr('href', function(index, attr) {
    return attr + '?' + foo;
});
Run Code Online (Sandbox Code Playgroud)

要么:

$('a#foo').attr('href', function() {
    return this.href + '?' + foo;
});
Run Code Online (Sandbox Code Playgroud)

  • 这将打破已经有查询字符串的网址.看看@ JohnC的回答. (2认同)

Joh*_*hnC 7

您需要先检查是否已有查询字符串,然后根据您执行的其他示例将项目附加到网址.

var foo = 'foo=bar';
$('a').attr('href', function(index, attr) {
    return attr + (attr.indexOf('?') >=0 ? '&' : '?') + foo;
});
Run Code Online (Sandbox Code Playgroud)