如何更新(附加到)jquery 中的href?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2805742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update (append to) an href in jquery?
提问by JD Isaacks
I have a list of links that all go to a google maps api.
我有一个链接列表,这些链接都指向谷歌地图 api。
the links already have the daddr
(destination) parameter in them as static. I am using Geo-Location to find the users position and I want to add the saddr
(source address) to the links once I get the data.
链接中已经有daddr
(目标)参数作为静态参数。我正在使用 Geo-Location 来查找用户位置,并且我想在saddr
获得数据后将(源地址)添加到链接中。
so basically I will need to add something like &saddr=50.1234567,-50.03452
at the tail end of all the links pointing to google maps
所以基本上我需要&saddr=50.1234567,-50.03452
在指向谷歌地图的所有链接的尾端添加一些东西
All the links have a class called directions-link
所有的链接都有一个叫做 directions-link
and from this pageI have figured out how to change them:
从这个页面我想出了如何改变它们:
$("a.directions-link").attr("href", "http://www.google.com/");
However I only want to append my value to the end of the href without changing what the href already is.
但是,我只想将我的值附加到 href 的末尾而不更改 href 已经是什么。
How can I do that?
我怎样才能做到这一点?
回答by Gabe
var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');
To loop with each()
循环使用 each()
$("a.directions-link").each(function() {
var $this = $(this);
var _href = $this.attr("href");
$this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});
回答by zaius
jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:
jQuery 1.4 有一个新特性来做这件事,它是规则。我忘记它叫什么了,但你这样使用它:
$("a.directions-link").attr("href", function(i, href) {
return href + '?q=testing';
});
That loops over all the elements too, so no need for $.each
这也会遍历所有元素,所以不需要 $.each
回答by Diodeus - James MacFarlane
$("a.directions-link").attr("href", $("a.directions-link").attr("href")+"...your additions...");
回答by Bikram Shrestha
Here is what i tried to do to add parameter in the url which contain the specific character in the url.
这是我尝试在 url 中添加包含 url 中特定字符的参数的方法。
jQuery('a[href*="google.com"]').attr('href', function(i,href) {
//jquery date addition
var requiredDate = new Date();
var numberOfDaysToAdd = 60;
requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd);
//var convertedDate = requiredDate.format('d-M-Y');
//var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
//console.log(requiredDate);
var month = requiredDate.getMonth()+1;
var day = requiredDate.getDate();
var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
//
Working Example Click
工作示例点击