为什么在JavaScript的相对路径中使用正斜杠'/'而不是反斜杠'\'?

Nik*_*hil 2 javascript image relative-path src

在我写的小JavaScript中,'img'元素的'src'属性只有在我在图像的相对路径中将'\'更改为'/'时才接受并显示图像.

为什么会这样?

<html>
  <body>

   <img id="image" src="F:\wallpapers\other\black-and-white-lion-chess-hd-531078.jpg">
   //why did '\' work here?

   <script>

    document.getElementById("image").src="F:/wallpapers/other/clouds_nature_skyscapes.jpg";
    //why didn't '\' work here? Why did I have to use '/' ?
  </script>

  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Ger*_*eon 5

\Javascript字符串中的单个字符用于"转义"下一个字符,例如\n用于换行符.看到这个

在您的示例中,如果要使用Windows路径名,请使用\\路径分隔符,如下所示:F:\\wallpapers\\other\\clouds_nature_skyscapes.jpg