jQuery - 单击更改图像src

时间:2013-04-21 09:48:23

标签: jquery

我希望能够通过点击两个不同的元素来更改图像的src,以便从一个图像更改为活动图像。

例如,如果单击.vehicle-desc-wrap或.vehicle-pic-wrap,我希望能够将此div中的图像网址从images/saloon-outline.png更改为images/saloon-outline-active.png,并且与所有其他汽车图像一样。

因此,例如,如果我点击轿车图像,网址将更改为saloon-outline-active.png,但如果我单击Executive Saloon图像,则会将执行图像的src更改为execsaloon-outline-active.png,并且每个其他图像都恢复正常状态(没有活动状态)。这是HTML: -

<div id="div-vehicle-wrap">

    <div id="div-Car" class="vehicle-item ui-corner-all req-wrapper">

    <div class="vehicle-pic-wrap ui-corner-left req-display success">

    <img class="vehicle-pic-ie6-png" height="100" width="120" alt="Standard Saloon" src="images/saloon-outline.png">

    </div>

    <div class="vehicle-desc-wrap req-display success">

    <div class="vehicle-radio-wrap">

    <div class="vehicle-accept-wrap">

</div>

<div id="div-Exec" class="vehicle-item ui-corner-all req-wrapper">

    <div class="vehicle-pic-wrap ui-corner-left req-display success">

    <img class="vehicle-pic-ie6-png" height="100" width="120" alt="Executive Saloon" src="images/execsaloon-outline.png">

    </div>

    <div class="vehicle-desc-wrap req-display success">

    <div class="vehicle-radio-wrap">

    <div class="vehicle-accept-wrap"></div>

</div>

到目前为止,我有以下内容: -

        $('img').click(function(){
            var src = this.src;
            this.src = src.indexOf('-active') == -1 ? src.replace('.png','-active.png') : src.replace('-active.png','.png');
        });

这不会将非活动图像更改回原始src,只会在单击实际图像而不是两个包装类时更改图像; .vehicle-desc-wrap or .vehicle-pic-wrap

如果有人可以帮助我,那将非常感激。

以下是该网站的链接:LINK

1 个答案:

答案 0 :(得分:1)

尝试

$(function(){
    var regexactive = /-active\..*$/;

    var ct = $('#div-vehicle-wrap');
    var imgs = $('.vehicle-pic-wrap img', ct);

    function deactiveImage(imgs){
        imgs.each(function(){
            var img = $(this);
            var src = img.attr('src');
            if( regexactive.test(src) ){
                img.attr('src', src.replace('-active.', '.'))
            }
        });
    }

    function activateImage(imgs){
        imgs.each(function(){
            var img = $(this);
            var src = img.attr('src');
            if( !regexactive.test(src) ){
                img.attr('src', src.replace('.png', '-active.png'))
            }
        });
    }

    ct.on('click', '.vehicle-desc-wrap', function(){
        var item = $(this).closest('.vehicle-item');
        deactiveImage($('.vehicle-pic-wrap img', item));
    });

    ct.on('click', '.vehicle-pic-wrap', function(){
        var item = $(this).closest('.vehicle-item');

        var img = $('.vehicle-pic-wrap img', item);
        deactiveImage(imgs.not(img))
        activateImage(img);
    });
})

演示:Fiddle