Comparing 2 Image's sources in Javascript

瘦欲@ 提交于 2021-01-24 12:36:26

问题


I'm trying to compare 2 images to see if they're the same. I've done quite a bit of research on this and can't come to a working conclusion. Here is an example of what I have now:

var image1 = document.getElementById('imgId1');
var image2 = document.getElementById('imgId2');
if(image1.src.match(image2.src)) {   <---This seems to only work w/ a string

  //do whatever here
}

I've also tried other things such as:

if(image2.src.indexOf(image1.src)!= -1)
{
    //do whatever here
}

and

if(image2.src == image1.src)
{

}

and

if(image2.src === image1.src)
{

}

I've tried using single quotes, double quotes, no quotes.. I haven't taken a Javascript class before so this kind of comparison is new to me. Any help would be great, thanks.

FULL CODE --

<script language="javascript">

function changeImage1() {

    var num = Math.floor((Math.random() * 48) + 1);
    var n = num.toString();
    var numImg = n.concat(".jpeg");
    var string = "/blah/blah/"
    var final = string.concat(numImg);
    var image = document.getElementById('imgClickAndChange1');
    var image2 = document.getElementById('imgClickAndChange2');
    if(image.src.match("blah.jpg")) {
        var num2 = Math.floor((Math.random() * 48) + 1);
        var n2 = num2.toString();
        var numImg2 = n2.concat(".jpeg");
        var final2 = string.concat(numImg2);
        image2.src = final2;
        image.src = final;
        if(image2.src == image.src){
            num2 = Math.floor((Math.random() * 48) + 1);
            n2 = num2.toString();
            numImg2 = n2.concat(".jpeg");
            final2 = string.concat(numImg2);
            image2.src = final2;
        }
    } else {
        image.src = final;
        if(image.src == image2.src){
            num = Math.floor((Math.random() * 48) + 1);
            n = num.toString();
            numImg = n.concat(".jpeg");
            final = string.concat(numImg);
            image.src = final;
        }

    }
}

I realize that there is still a slight chance the images will be the same after the 2nd rand. -- Script will still put images as the same in the 1st pass


回答1:


The double equals '==' should be fine. Try outputting the values when it fails to see what's up.

if(image2.src == image1.src)
{

}
else
{
    console.log([image2.src, image1.src]);
    alert("They did not match because 1 is " + image1.src + " and 2 is " + image2.src);
}


来源:https://stackoverflow.com/questions/33394937/comparing-2-images-sources-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!