'替换'改变整个src而不只是结束..为什么?

时间:2014-11-10 20:59:30

标签: javascript jquery

情况: 我有十个灰色div(每个都带有图像和文本)作为按钮。我希望按钮在激活时具有较暗的文本和较暗的图像。单击活动按钮时,我希望它取消激活。我还想让它在另一个按钮变为活动状态时停用。

问题: 当我替换图像源上的结尾时,它会将图像上的完整源更改为与活动源相同的...将所有其他图像更改为相同的图标。

的jsfiddle: http://jsfiddle.net/messedUP90/gtf1dk0m/

警告: jsfiddle显示我遇到的问题,所有其他图像变为相同,但由于某种原因,活动图像不会改变颜色。它在Dreamweaver中工作正常,所以我不太关心它。

$(document).ready(function(){
    var x = 300;
    $("[id^=pport]").click(function () {
        var src = $('.butt', this).attr('src');
        if($(this).hasClass('highlight')){
            $(this).removeClass('highlight');
            $('.butt', this).attr('src', src.replace(/_dark(\.[^.]+)?$/, '_light$1'));
        }
        else{
            $('.butt').removeClass('highlight');
            $('.butt').attr('src', src.replace(/_dark(\.[^.]+)?$/, '_light$1'));
            $('.talk').fadeOut(x);
            $(this).addClass('highlight');
            $('.butt', this).attr('src', src.replace(/_light(\.[^.]+)?$/, '_dark$1'));
        }
    });
});

2 个答案:

答案 0 :(得分:1)

问题与您描述的一样 - 您要将每个图标的src更改为您点击的图标的src,只需将lightdark进行交换

即。在您设置var src = $('.butt', this).attr('src');

的早期

然后,您不会将变量src重新设置为其他任何内容。

然后你$('.butt').attr('src', src.replace(/_dark(\.[^.]+)?$/, '_light$1'));

这会将src类的所有元素的butt属性设置为所点击图标的简易版本。

你问题出在哪里......

不是简单地尝试一次性更改图像,而是需要遍历完整集:

$('.butt').each( function( index ) {
    if ( $(this).attr('src') ) {
        $(this).attr('src', $(this).attr('src').replace(/_dark(\.[^.]+)?$/, '_light$1'));
    } 
});

小提琴(工作但与你的光/暗限制相同)在这里:http://jsfiddle.net/gtf1dk0m/1/

答案 1 :(得分:0)

$('.butt').removeClass('highlight');

highlight类的每个元素中删除butt类。同样,对于属性替换。您需要改为使用$(this)

相关问题