点击不下载图片,而不是打开图片网址

时间:2019-02-26 21:48:51

标签: javascript html5

点击下载图片时遇到问题,它打开了图片的URL,而不是下载。我也尝试过其他StackOverflow答案,但没有什么能真正解决我的问题

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <a class="d1" href="https://cdn.shopify.com/s/files/1/1816/0091/files/Artboard_3_1.png?11554335258293208175" download="aa.jpg">
    <img  src="https://cdn.shopify.com/s/files/1/1816/0091/files/Artboard_3_1.png?11554335258293208175" width="104" height="142">     <span>Click to Download</span>
  </a>
  <script>
    document.querySelector(".d1").setAttribute("download", "filename.jpg");
  </script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

  1. 您的课程是d1,但在.getElementsByClassName()中,您 搜索dl
  2. 您的代码尝试在元素具有之前找到该元素 被解析为文档,因此您需要将脚本移至 网页的底部,以便在代码执行时, 元素将被解析。
  3. 您在filename.jpg前面缺少开头引言
  4. .getElementsByClassName()是错误的选择,因为它返回一个 “活动”节点列表(仅在某些用例和 会损害所有其他方面的性能),并且因为您不感兴趣 在节点列表中,您试图仅找到一个元素。采用 改为.querySelector()

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <a class="d1" href="https://cdn.shopify.com/s/files/1/1816/0091/files/Artboard_3_1.png?11554335258293208175" download="aa.jpg">
    <img  src="https://cdn.shopify.com/s/files/1/1816/0091/files/Artboard_3_1.png?11554335258293208175" width="104" height="142">     <span>Click to Download</span>
  </a>
  <script>
    document.querySelector(".d1").setAttribute("download", "filename.jpg");
  </script>
</body>
</html>

相关问题