通过 DOM 设置 src 与比较 src 值

Setting src through DOM vs Comparing src values

我有一个像这样的 img 标签

<img id="fish" src="">

然后我通过 setInterval 函数随机设置和更改了 img 的 src

var randFish = Math.floor(Math.random() * 2);

if(randFish == 0) document.getElementById('fish').src = "images/fish.png";
else if(randFish == 1) document.getElementById('fish').src = "images/fishbone.png";

这段代码运行良好,图像路径已成功添加到 src,但是当我尝试比较此 src 是否等于该路径时,它 returns false always

console.log(document.getElementById('fish').src == "images/fish.png"); //output: false
console.log(document.getElementById('fish').src == "images/fishbone.png"); //output: false

当我尝试在控制台中 return src

console.log(document.getElementById('fish').src); //output: file:///C:User/Desktop/.../images/fishbone.png

以这种方式使用图像路径进行比较是可行的,但为什么会发生这种情况,是否有比使用整个路径(如 "file:///C:User/Desktop/.../images/fishbone.png

const img_  = document.getElementById('img_');
img_.fish_  = ['fish.png', 'fishbone.png'];
img_.path_  = 'images/';

img_.change_ = function(){
  let random_ = Math.floor(Math.random() * this.fish_.length);
  img_.src = `${this.path_}${this.fish_[random_]}`;
  console.clear(); console.log(img_.src);
}
<img id="img_" src="" />
<button onclick="img_.change_();">Randomly change fish</button>

<!--
   /   = Root directory
   .   = This location
   ..  = Up a directory
   ./  = Current directory
   ../ = Parent of current directory
   ../../ = Two directories backwards
-->

这是因为,正如您在尝试时看到的那样

console.log(document.getElementById('fish').src);

element.src 属性 return 元素的完整 url。您要查找的是 src 属性的值。所以尝试:

console.log(document.getElementById('fish').getAttribute('src') == "images/fish.png"); 

哪个应该 return true.