【问题标题】:Can not set image src via jquery / javascript无法通过 jquery / javascript 设置图像 src
【发布时间】:2020-01-09 21:35:29
【问题描述】:

我有一张需要通过 jquery 或 javascript 动态设置的图片

<img id="myImage" src="" />

我的视图名为“UserProfile”,我的控制器名称为“User”,生成的 url 为:https://localhost/Carpool.Web/User/UserProfile

我的图片位于 wwwroot/images 文件夹下

现在当我使用以下任何一种时,我得到 404 并且图像不显示:

$("#myImage").attr({ "src": "/wwwroot/images/info.png" }); //console => <img id="myImage" src="https://localhost/Carpool.Web/User/UserProfile/wwwroot/images/info.png">
$("#myImage").attr({ "src": "~/images/info.png" });//console => <img id="myImage" src="~/images/info.png">
$("#myImage").attr({ "src": "/images/info.png" });//console => <img id="myImage" src="https://localhost/Carpool.Web/User/UserProfile/images/info.png">
$("#myImage").attr({ "src": "images/info.png" }); //console => <img id="myImage" src="https://localhost/images/info.png">
document.getElementById("myImage").src // tried all as above 

如果我的视图是“索引”,那么我没有这个问题,网站徽标也可以正常显示 这与我升级到 asp.net core 3.1 有关吗?

【问题讨论】:

  • 听起来你的图像有绝对路径。这就是为什么如果这些页面与索引不在同一级别,它将在索引而不是其他页面上工作。然后,您必须先导航到正确的文件夹才能获取图像。
  • 有没有办法解决这个问题?我不想硬编码完整路径,因为我们有不同的环境
  • my images located under wwwroot/images folder你确定用https://localhost/images/&lt;image_file_name&gt;确实无法访问图片吗?请分享您的项目文件夹结构,以便我们更好地解决问题。

标签: javascript jquery asp.net-core


【解决方案1】:

我需要查看您的树结构来更正它。

放“。”或路径前面的“..”

例如

"src": "./wwwroot/images/info.png" // 仅当图像文件夹与您的页面具有相同的父文件夹时

"src": ../wwwroot/images/info.png"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2018-06-08
    • 2018-07-14
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    相关资源
    最近更新 更多