jQuery替换href值,但仅部分替换? [英] jQuery replace href value but only partially?
问题描述
可能重复:
使用jQuery更改href参数
Possible Duplicate:
Change href parameter using jQuery
我的页面上有几个这样的链接:
I have a page with several links like this:
<a href="playcats.php?cat='.$catname.'&sl=10" class="golink">
因此,在PHP页面加载后,它看起来像:
So after PHP page loads it will look like:
<a href="playcats.php?cat=blue&sl=10" class="golink">
<a href="playcats.php?cat=red&sl=10" class="golink">
<a href="playcats.php?cat=yellow&sl=10" class="golink">
...
我想使用jQuery部分更改所有链接的sl值的href(从滑块中选择sl值= data.value)
I want partially change the href for the sl value of all links using jQuery (sl value is picked from a slider = data.value)
我有这个:
$(document).ready(function() {
$('a.golink').each(function() {
var _href = $(this).attr('href');
$(this). ( rest of code.. )
} );
});
现在我不知道如何使用正则表达式替换,因为我认为这是解决方案!
And now I do not know how to use replace with regular expressions as I think it is the solution!
推荐答案
您可能会
$(this).attr('href', _href.replace(/sl=[^&]+/, 'sl=newval'));
用'newval'替换sl
的值.
to replace the value of sl
by 'newval'.
您还可以使用一个函数来构建新值.例如,假设您要将旧的sl值乘以2,则可以执行以下操作:
You can also use a function to build the new value. For example, say you want to multiply by 2 the old sl value, you may do this :
$(this).attr('href', _href.replace(/sl=([^&]+)/, function(_, oldval) {
return 'sl='+(2*parseInt(oldval,10))
}));
您甚至可以避免使用each
:
$('a.golink').attr('href', function(i, v){
return v.replace(/sl=([^&]+)/, function(_, oldval) {
return 'sl='+(2*parseInt(oldval,10))
})
});
演示(通过链接查看href)
Demonstration (over the links to see the href)
这篇关于jQuery替换href值,但仅部分替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!