开发者

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

开发者 https://www.devze.com 2023-01-18 18:23 出处:网络
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:

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(开发者_StackOverflow社区));
});

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

精彩评论

暂无评论...
验证码 换一张
取 消