Change href value using jQuery

后端 未结 4 602
野性不改
野性不改 2020-12-03 08:39

How do I rewrite an href value, using jQuery?

I have links with a default city

parks
&         


        
相关标签:
4条回答
  • 2020-12-03 08:59
     $('a').attr("href", "/search/?what=parks&city=" + newCity);
    
    0 讨论(0)
  • 2020-12-03 09:02

    As soon as a key is released within the #city input field, the href will be updated.

    $('#city').keyup(function(){
    
        $('a').attr('href','/search/?what=parks&city='+$(this).val());
    
    });
    
    0 讨论(0)
  • 2020-12-03 09:07

    Like this:

    var newCity = $("#city").val();
    
    $('a').attr('href', '/search/?what=parks&city=' + newCity);
    

    EDIT: Added the search string

    0 讨论(0)
  • 2020-12-03 09:11

    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/

    0 讨论(0)
提交回复
热议问题