开发者

Replace URL parameter values in links using JavaScript/jQuery?

开发者 https://www.devze.com 2023-03-24 04:57 出处:网络
My CMS\'s lightbox-style photo gallery outputs code like below. I\'ve provided code for two thumbnails.

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 sugges开发者_运维问答tion, 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/.

0

精彩评论

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