Javascript 使用 jQuery 更改 href 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6540106/
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
Change href value using jQuery
提问by ram1
How do I rewrite an href value, using jQuery?
如何使用 jQuery 重写 href 值?
I have links with a default city
我有一个默认城市的链接
<a href="/search/?what=parks&city=Paris">parks</a>
<a href="/search/?what=malls&city=Paris">malls</a>
If the user enters a value into a #city textbox I want to replace Paris with the user-entered value.
如果用户在 #city 文本框中输入一个值,我想用用户输入的值替换 Paris。
So far I have
到目前为止我有
var newCity = $("#city").val();
回答by Sampson
Given you have unique href
values (?what=parks
, and ?what=malls
) I would suggest notwriting a path into the $.attr()
method; you would have to have one call to $.attr()
for each unique href
, and that would grow to be very redundant, very quickly - not to mention difficult to manage.
鉴于您有唯一href
值(?what=parks
, 和?what=malls
),我建议不要在$.attr()
方法中写入路径;您必须$.attr()
为每个独特的调用一个href
,这将变得非常多余,非常快 - 更不用说难以管理了。
Below I'm making one call to $.attr()
and using a function to replace only the &city=
portion with the new city. The good thing about this method is that these 5 lines of code can update hundreds of links without destroying the rest of the href
values on each link.
下面我正在调用$.attr()
并使用一个函数来仅用&city=
新城市替换该部分。这种方法的好处在于,这 5 行代码可以更新数百个链接,而不会破坏href
每个链接上的其余值。
$("#city").change(function(o){
$("a.malls").attr('href', function(i,a){
return a.replace( /(city=)[a-z]+/ig, ''+o.target.value );
});
});
One thing you may want to watch out for would be spaces, and casing. You could convert everything to lower case using the .toLowerCase()
JavaScript method, and you can replace the spaces with another call to .replace()
as I've down below:
您可能需要注意的一件事是空间和外壳。您可以使用.toLowerCase()
JavaScript 方法将所有内容转换为小写,并且您可以使用另一个调用替换空格,.replace()
如下所示:
''+o.target.value.replace(/\s+/, '');
Online Demo: http://jsbin.com/ohejez/
在线演示:http: //jsbin.com/ohejez/
回答by AndyL
$('a').attr("href", "/search/?what=parks&city=" + newCity);
回答by Kokos
As soon as a key is released within the #city
input field, the href
will be updated.
只要在#city
输入字段内释放一个键,href
就会更新。
$('#city').keyup(function(){
$('a').attr('href','/search/?what=parks&city='+$(this).val());
});
回答by Phil
Like this:
像这样:
var newCity = $("#city").val();
$('a').attr('href', '/search/?what=parks&city=' + newCity);
EDIT:Added the search string
编辑:添加了搜索字符串