0

I have a number of urls, and I'm wondering if there's a way to dynamically change the last digit of them.

    <div class="m_item">
        <a class="thumbnail_link" href="http://paraboladesignstudio.ipage.com/yahaira/fashion/fashion-slideshow/?thumb=0">
            <img src="<?php echo $image['sizes']['thumbnail'];?>" title="<?php echo $image['title'];?>" alt="<?php echo $image['alt']; ?>"> 
        </a>
    </div>  

The above code outputs certain number of ".m_item"s with the same "a href"s.

This is my jQuery code:

var i=0;
i++;

$(".thumbnail_link").each(function() {
    this.href = this.href.replace("0", i);
});

It changed all the urls to "..../?thumb=1"

How could I make the digit increase? I've tried .children with no luck.

Thank you.

2
  • At least try: $(".thumbnail_link").each(function(i) { this.href = this.href.replace("0", i); }); and remove your i declaration Commented Mar 19, 2014 at 19:08
  • 2
    beat you by 3 seconds Commented Mar 19, 2014 at 19:09

3 Answers 3

3

Get rid of the i and just use the index of the each() https://api.jquery.com/each/

$(".thumbnail_link").each(function(index) {
    this.href = this.href.replace("0", index);
});

Or you can do this in case there are other 0s in the url

$(".thumbnail_link").each(function(index) {
    this.href = this.href.replace("thumb=0", "thumb=" + index);
});
Sign up to request clarification or add additional context in comments.

7 Comments

what happened when the url string have other "0" s ..?
From the way the OP asked, it seems there is only one 0, but you can always replace the entire thumb=0
Thank you, but then the url starts from 1, but it should start from 0. I tried i-1 but only got an error.
now the answer more close to his needs i think +1 for u
Just take 1 off from the index
|
2

It's doing that because i is only ever incremented once. It starts out as zero, then you bump it up to 1 with i++, and then you never change it again. Try this:

$(".thumbnail_link").each(function(i) {
    this.href = "http://paraboladesignstudio.ipage.com/yahaira/fashion/fashion-slideshow/?thumb=" + i;
});

Comments

1

or if you want to update the last number, use this

$(".thumbnail_link").each(function(index) {
    this.href = this.href.replace(/([\d]+)$/g, index);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.