简体   繁体   English

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

[英]Why use forward slash '/' instead of backward slash '\' in relative paths in JavaScript?

In the little JavaScript I wrote, the 'src' attribute of 'img' element accepted and displayed the image only if I changed '\\' to '/' in the relative path of the image. 在我写的小JavaScript中,仅当我在图像的相对路径中将'\\'更改为'/'时,'img'元素的'src'属性才被接受并显示图像。

Why is it so? 为什么会这样呢?

<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>

A single \\ character in a Javascript string is used to "escape" the next character, eg \\n is used for the newline character. Javascript字符串中的单个\\字符用于“转义”下一个字符,例如\\n用作换行符。 See this 看到这个

In your example, if you want to use windows path names, use \\\\ as path separator, like so: F:\\\\wallpapers\\\\other\\\\clouds_nature_skyscapes.jpg 在您的示例中,如果要使用Windows路径名,请使用\\\\作为路径分隔符,如下所示: F:\\\\wallpapers\\\\other\\\\clouds_nature_skyscapes.jpg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM