onclick заменяет все изображения с меньшим номером в src (jQuery)

У меня есть термометр, построенный из 10 изображений. Я хотел бы изменить каждую секцию (изображение) термометра по нажатию, например, если вы щелкнете по 3-му изображению (равному 30 градусам), изображения под ним (термо2 и термо1) также изменятся. Это работает со следующим (по общему признанию громоздким) кодом:

<img src="thermo01_off.png" id="thermo1" class="img-swap" alt="10°" width="157" height="33" />
<img src="thermo01_off.png" id="thermo2" class="img-swap" alt="20°" width="157" height="33" />
<img src="thermo03_off.png" id="thermo3" class="img-swap" alt="30°" width="157" height="33" />
... and so on

$(function(){
    $(".img-swap").on('click', function() {
       if ($(this).attr("id") == "thermo1") {
           thermo1.src = thermo1.src.replace("_off","_on");
       } else if ($(this).attr("id") == "thermo2") {
           thermo1.src = thermo1.src.replace("_off","_on");
           thermo2.src = thermo2.src.replace("_off","_on");
       } else if ($(this).attr("id") == "thermo3") {
           thermo1.src = thermo1.src.replace("_off","_on");
           thermo2.src = thermo2.src.replace("_off","_on");
           thermo3.src = thermo3.src.replace("_off","_on");
       }
 });

Проблема 1 В настоящее время изображения не переключаются обратно. Я знаю, что вы можете использовать "toggleClass", но я не уверен, как реализовать в приведенном выше коде.

Задача 2 Если я реализую приведенный выше код для всех 10 изображений термометра, он получится довольно длинным. Должен быть намного более эффективный способ написания вышеупомянутого. Какие-либо предложения.

Решение Этот код сработал в конце, спасибо также Греггу.

$(function() {
  $("[id^=thermo]").click(function() {
    var notid, thisid, new_url, not_url = "";
    var $this = $(this);

    //Get the ID without the "thermo" part
    thisid = $this.attr('id').replace('thermo', '');

    //swap image that was clicked
    new_url = $this.attr('src').replace("_off", "_on");
    $(".img-swap" + thisid).attr("src", new_url);

    //replaces all images that were NOT clicked
    $("[id^=thermo]").not(this).attr('id', function(i, idx) {

        //get ids of those not clicked
        notid = idx.replace('thermo', '');

        //change src of images with lower ids than the clicked one
        if (notid < thisid) {
            not_url = $(".img-swap" + notid).attr('src').replace("_off", "_on");
            console.log(notid);
            $(".img-swap" + notid).attr("src", not_url);
        } else {
            not_url = $(".img-swap" + notid).attr('src').replace("_on", "_off");
            $(".img-swap" + notid).attr("src", not_url);
        }
    });
});

});

1 ответ

Решение

Примерно так должно работать:

$(function(){
// add click event listener to all imgs with id starting with 'thermo'
$('img[id^="thermo"]').click(function(){
    // get the index of the clicked element in the array of all matching elements
    var idx = $(this).index();
    // edit the src of the elements with an index less than the clicked element
    $.each($('img[id^="thermo"]'), function(i, img){
        if($(img).index() <= idx){
            $(img).attr('src', $(img).attr('id') + '_on');
        }else{
            $(img).attr('src', $(img).attr('id') + '_off');
        }
    });
});

});

РЕДАКТИРОВАТЬ: Пока идентификатор изображения совпадает с именем файлов изображений, как показывает ваш пример HTML. это будет работать Я изменил его на цикл и используя идентификаторы для установки изображения src.

Другие вопросы по тегам