开发者

How to append variable to url in jquery?

开发者_运维知识库How can I append variable/text to the attribute href in jquery ?


You could use the .attr() function:

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

or:

$('a#foo').attr('href', function() {
    return this.href + '?' + foo;
});


You need to check if there is already a query string before appending items to the url based on the other examples you'd do something like.

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


$('a').attr('href', function(i, v) {
    return v + 'text...';
});


If you use it repeatedly try .attr() as:

HTML: <a id='foo' href='#'>I am your father,.. nooooo</a>

var myparams = 'myvar=myvalue';
var myurl = 'TypeThe_NetscapeURL';
$('a#foo').attr('href', function() {
    return myurl + '?' + myparams;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜