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 elementi
(First Parameter) - The index of the element in the setoldHref
(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);
});
精彩评论