Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - Change href value using jQuery

How do I rewrite an href value, using jQuery?

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.

So far I have

var newCity = $("#city").val();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 );
  });
});

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+/, '');

Online Demo: http://jsbin.com/ohejez/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...