Increment href values using jQuery:
Suppose you have a link that contains some values:
<a href="/action?number_one=1&number_two=4" class="some_link"> something </a>
How can you increment number_one and number_two when a user clicks on this link using jQuery?
I know to extract number_one's value you can use regex:
var number_one = $(this).attr("href").match(/number_one=([0-开发者_运维问答9]+)/)[1];
How can you then increment it say by 20, so that it now becomes:
<a href="/action?&number_one=21&number_two=24" class="some_link"> something </a>
This works in Chrome, at least - the .search
attribute is an HTML5 property:
// get the real link element
var link = $(this).get(0);
var fields = {};
// parse and increment number one
fields.number_one = link.search.match(/number_one=([0-9]+)/)[1];
fields.number_one += 20;
// do same for number two:
fields.number_two = link.search.match(/number_two=([0-9]+)/)[1];
fields.number_two += 20;
// update the link's query parameters
link.search = $.param(fields);
This should do it for any number of url-query var=number
pairs:
var fixed_url = $(this).attr("href").replace(
// This regex matches a url-query var=number
/([?&]\w+=)(\d+)(?=[&#]|$)/g,
// This function increments the value by one.
function(m0, m1, m2) {
return m1 + (Number(m2) + 1);
});
Edit: Removed invalid jQuery assignment.
精彩评论