简体   繁体   中英

Replace URL parameter values in links using JavaScript/jQuery?

My CMS's lightbox-style photo gallery outputs code like below. I've provided code for two thumbnails.

The parameter values for "m" and "s" will always be "150" and "true." I'd like to change that to m=250 and s=false.

I'm new to JavaScript and jQuery. If you have a suggestion, please help me out with where to put the code on the page. Thank you.

<div class="thumbTight MainContent">
    <div class="thumbContents">
        <a href="/PhotoGallery/banana.jpg" rel="lightbox[2065379]" title="Banana">
            <img src="/ResizeImage.aspx?img=/PhotoGallery/banana.jpg&amp;m=150&amp;s=true" alt="Banana" />
        </a>
        <div class="description" style="display: none;"></div>
    </div>
</div>

<div class="thumbTight">
    <div class="thumbContents">
        <a href="/PhotoGallery/cantaloupe.jpg" rel="lightbox[2065379]" title="Cantaloupe">
            <img src="/ResizeImage.aspx?img=/PhotoGallery/cantaloupe.jpg&amp;m=150&amp;s=true" alt="Cantaloupe" />
        </a>
        <div class="description" style="display: none;"></div>
    </div>
</div>

In your document ready handler, use each to iterate over the thumbnails (images inside divs with the thumbContents class) and assign the src attribute to the original src attribute with the required substitutions.

$(function() {
    $('.thumbContents img').each( function() {
        var $img = $(this);
        $img.attr('src', $img.attr('src').replace(/m=150/,'m=250').replace(/s=true/,'s=false') );
    });
});

You can run this jQuery after the page has loaded. The images will start loading with the different URL, your code will run and change the image URLs and then the new one will load and display. There is nothing you can do client-side to prevent the initial display unless you actually use CSS such that they images are initially hidden and only made visible AFTER you've set the desired URL.

$(".thumbTight img").each(function() {
    this.src = this.src.replace(/m=150/, "m=250").replace(/s=true/, "s=false");
});

You can see a demo here: http://jsfiddle.net/jfriend00/UdnFE/ .

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