I have a bunch of links on a page that on an action, I run a function and it appends an extra variable like so:
我在页面上有一堆链接,在一个动作上,我运行一个函数,它会附加一个额外的变量,如下所示:
function storeId(uID) {
$('a.special').each(function(){
$(this).attr('href',$(this).attr('href')+'&variable='+uID+'');
});
}
My understanding is, the above would go through each link identified, and grab the existing href, then append the variable bits onto the end. I have got the variable appending, but its not working as expected... e.g its appending the '&variable=' part twice, the first time, like '&variable=undefined' and then on top of that '&variable=23'.
我的理解是,上面将通过识别的每个链接,并获取现有的href,然后将变量位附加到末尾。我有变量追加,但它没有按预期工作...例如,它附加'&variable ='部分两次,第一次,如'&variable = undefined',然后在'&variable = 23'之上。
Is there a better way to do this? Or a way I can just say go through each of these links and simply update the value that is set to the variable rather than rewriting the whole href?
有一个更好的方法吗?或者我只能说通过这些链接中的每一个并简单地更新设置为变量的值而不是重写整个href?
So just to re-iterate, my original link is just something like this:
所以只是为了重新迭代,我原来的链接是这样的:
<a class="special" href="/page.php?random=1">link name</a>
And the aim is to have it look like the following after the function is performed:
目的是在执行函数后让它看起来像下面这样:
<a class="special" href="/page.php?random=1&variable=32">link name</a>
But it winds up looking like:
但它看起来像:
<a class="special" href="/page.php?random=1&variable=undefined&variable=32">link name</a>
2 个解决方案
#1
Are you sure that storeId isn't getting called twice? seems like it is.
你确定storeId没有被调用两次吗?看起来像是。
#2
function storeId(uID) {
$('a.special').each(function(){
link = $(this).attr('href');
nlink = link + '&variable='+uID;
$(this).attr('href', newlink);
});
}
Give that a try.
试一试。
#1
Are you sure that storeId isn't getting called twice? seems like it is.
你确定storeId没有被调用两次吗?看起来像是。
#2
function storeId(uID) {
$('a.special').each(function(){
link = $(this).attr('href');
nlink = link + '&variable='+uID;
$(this).attr('href', newlink);
});
}
Give that a try.
试一试。