简体   繁体   中英

When changing the href attribute of a link using jQuery, how do I reference the current href attribute?

I'm trying to change the href attribute of links on my page. I need the bulk of the url to remain the same but just change a parameter. I've got this so far:

$("a[href*='/new_note?']").attr('href', function() {
    return this.replace(/date1=[\d-]+/, "date1=" + $("[name='new_date1']").val());
});

but I'm getting this error:

this.replace is not a function

What am I doing wrong? Thanks for reading.

It's the second parameter of the function you're passing into .attr() , like this:

$("a[href*='/new_note?']").attr('href', function(i, oldHref) {
    return oldHref.replace(/date1=[\d-]+/, "date1=" + $("[name='new_date1']").val());
});

For this function:

  • this - The current DOM element
  • i (First Parameter) - The index of the element in the set
  • oldHref (Second Parameter) - The current value of the attribute

A side suggestion here, just a [name='new_date1'] attribute-equals selector is quite expensive, if you know the element type add it on to make it much faster, for example:

$("input[name='new_date1']").val()

Then to make it even faster, fetch the value once before this .attr() function (which runs for every element), so you're only fetching that value once, like this:

var newDate = $("input[name='new_date1']").val();
$("a[href*='/new_note?']").attr('href', function(i, oldHref) {
  return oldHref.replace(/date1=[\d-]+/, "date1=" + newDate);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM