JS:根据页面URL获取图片

JS: Getting an image based on the page URL

本文关键字:URL 获取 取图片 JS      更新时间:2024-05-13

请原谅我的无知;我是一个HTML爱好者,JS对我来说很陌生。我正在尝试创建一个基于页面URL显示图像的函数。

例如:"page_001-e.html"将显示"page_001.jpg"

到目前为止,我已经设法把这件事处理掉了。

<script type="text/javascript">
  document.write("<img src='"photos/full/"+location.pathname.substring(location.pathname.lastIndexOf("/") + 1)+".jpg"+"'" />");
</script>

哪个返回:

 <img url="photo_000-e.html.jpg" />

我需要从结果中修剪-e.html。我在一个多语言网站工作,所以我不能依赖-e作为常量,因为它是语言指标。

从谷歌上看,我可以使用str.replaceslice,但我不知道如何使用它们,也不知道从这里到哪里。

如果我看错了这件事,我会感谢任何帮助或建议。

您可以使用以下代码获得图像的URL,假设总是有一个短划线:

<script type="text/javascript">
    var img_url = window.location.href.split("-")[0] + ".jpg";
</script>

现在,你需要弄清楚你想把它放在哪里。我建议你制作一个Image对象,然后把它附加到DOM中的一个特定区域。

<script type="text/javascript">
    // Get the image URL
    var img_url = window.location.href.split("-")[0] + ".jpg";
    // Create an image (not visible anywhere)
    var img = document.createElement("img");
    // Set the Image to load from your new URL
    img.src = image_url;
    // Add it to your HTML
    document.getElementById("some_id").appendChild(img);
</script>
<div id="some_id">
</div>

在上面的代码中,javascript会将图像添加到ID为"some_ID"的div中。

您可以使用以下代码来修剪值

location.pathname.substring(location.pathname.lastIndexOf("/") + 1).replace(location.pathname.substring(location.pathname.lastIndexOf("/") + 1).lastIndexOf("-"),"")

是否尝试替换?

var path = location.pathname.replace('.html','.jpg');
document.write(path);