单击按钮替换图像src属性中的文件夹名称

时间:2018-12-03 09:34:27

标签: javascript jquery html css

在单击按钮/触发器时,我需要将特定类“ .imageShift”的所有实例的文件夹路径名从img / image.jpg更改为imgdark / image.jpg。插入图像src中的任何图像名称在所有情况下都应保持不变。只需将“ img”文件夹路径替换为“ imgdark”即可。我尝试了下面给出的代码。

$('.themeColor').click(function () {
    var getId = $(this).attr('id');
    var imagePath = $('.imagePath');
    if (getId === 'darkTheme') {

        imagePath.attr('src', function (index, attr) {
            return attr.replace('img', 'imgdark');
        });
    } else if (getId === 'lightTheme') {
        imagePath.attr('src', function (index, attr) {
            return attr.replace('imgdark', 'img');
        });
    }
});

上面的代码运行正常,但是每次单击都会出现控制台错误,如下所示。我需要摆脱该控制台错误,并像现在一样使它工作。如果有人已经这样做,请提供帮助。

Uncaught TypeError: Cannot read property 'replace' of undefined
at HTMLLIElement.<anonymous> (homepage.js:1619)
at z (jquery-3.3.1.min.js:2)
at w.fn.init.attr (jquery-3.3.1.min.js:2)
at HTMLSpanElement.<anonymous> (homepage.js:1617)
at HTMLSpanElement.dispatch (jquery-3.3.1.min.js:2)
at HTMLSpanElement.y.handle (jquery-3.3.1.min.js:2)

3 个答案:

答案 0 :(得分:1)

使用此:

$('.themeColor').click(function () {
var getId = $(this).attr('id');
var imagePath = $('.imagePath');
if (getId === 'darkTheme') {

    imagePath.attr('src', 'imgdark/image.jpg');
} else if (getId === 'lightTheme') {
    imagePath.attr('src', 'img/image.jpg');
}

});

答案 1 :(得分:1)

您可以执行以下操作:

$('.themeColor').click(function () {
  $('.themeColor').removeClass('themeActive');
     var getId = $(this).attr('id');
     var imagePath = $('.imagePath');
     if (getId === 'darkTheme') {
      imagePath.attr('src', imagePath.attr('src').replace('img/', 'imgdark/'));
     } else if (getId === 'lightTheme') {
       imagePath.attr('src', imagePath.attr('src').replace('imgdark/', 'img/'));
     }

    $('.imagePath').each(function(index, val) {
     console.log('You changed the image('+(index+1)+') path to:'+$(this).attr('src'))
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="themeColor" id="darkTheme">Dark</button>
<button class="themeColor" id="lightTheme">Light</button>


<img class="imagePath" src="imgdark/sampleimg.jpg" alt="">
<img class="imagePath" src="imgdark/sampleimg.jpg" alt="">

答案 2 :(得分:0)

使用此:

    $('.themeColor').click(function () {
    var getId = $(this).attr('id');
    var imagePath = $('.imagePath');
    if (getId === 'darkTheme') {

        imagePath.attr('src', function (index, attr) {
            if attr {
              return attr.replace('img/', 'imgdark/');
           }
        });
    } else if (getId === 'lightTheme') {
        imagePath.attr('src', function (index, attr) {
            if attr {
                 return attr.replace('imgdark/', 'img/');
}
        });
    }
});