使用jQuery更改href值 [英] Change href value using jQuery

查看:126
本文介绍了使用jQuery更改href值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jQuery重写href值?

How do I rewrite an href value, using jQuery?

我有默认城市的链接

<a href="/search/?what=parks&city=Paris">parks</a>
<a href="/search/?what=malls&city=Paris">malls</a>

如果用户在#city文本框中输入值,我想用用户输入的内容替换Paris价值。

If the user enters a value into a #city textbox I want to replace Paris with the user-entered value.

到目前为止,我已经

var newCity = $("#city").val();


推荐答案

鉴于您有独特的 href 值(?what = parks ?what = malls )我建议 not 将路径写入 $。attr()方法;对于每个唯一的 href ,您必须有一次 $。attr()的调用,这将会增长到非常多余,非常快 - 更不用说难以管理了。

Given you have unique href values (?what=parks, and ?what=malls) I would suggest not writing 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.

下面我打电话给 $。attr()并使用一个函数仅用新城市替换& city = 部分。这种方法的好处是这5行代码可以更新数百个链接,而不会破坏每个链接上的其余 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.

$("#city").change(function(o){
  $("a.malls").attr('href', function(i,a){
    return a.replace( /(city=)[a-z]+/ig, '$1'+o.target.value );
  });
});

您可能需要注意的一件事是空格和套管。您可以使用 .toLowerCase() JavaScript方法将所有内容转换为小写,并且可以使用对 .replace()<的另一个调用替换空格/ code>正如我在下面所说:

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:

'$1'+o.target.value.replace(/\s+/, '');

在线演示: http://jsbin.com/ohejez/

这篇关于使用jQuery更改href值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆