onclick替换src(jQuery)

时间:2015-11-05 18:11:34

标签: jquery image onclick toggleclass

我有一个由10张图像构成的温度计。我想改变温度计的每个部分(图像),例如,如果你点击第三张图像(等于30度),它下面的图像(thermo2和thermo1)也会改变。这适用于以下(公认的繁琐)代码:

<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 目前,图片不会切换回来。我知道您可以使用&#34; toggleClass&#34;,但我不确定如何在上面的代码中实现。

问题2 如果我为所有10个温度计图像实现上述代码,它将会很长。必须有一种更有效的方式来编写上述内容。任何建议。

解决方案 这段代码最终也有效,感谢Gregg。

$(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 个答案:

答案 0 :(得分: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');
        }
    });
});

});

编辑:只要图像的id与图像文件的名称相同,就像示例html显示的那样。这会奏效。我将其更改为循环并使用ID设置图像src。