简体   繁体   中英

set src img tag in javascript

What the proper way to set src in img tag from js into asp.net? Because I try this way, it doesn't show up. The data from sql server and I'm using jquery and ajax to call the data. It's already show up in console but don't know why it be like that

In console

<img class="img-fluid px-3 px-sm-4 mt-3 mb-4" id="img" style="width: 25rem;" alt="learning" src="~/images/Capture205450514.PNG">

.js

let q = data[questionIndex];
    if (q.img != null) {
        $("#img").attr("src", q.img);
    }
    else {
        img.style.display = "none";
    }

.cshtml

<img class="img-fluid px-3 px-sm-4 mt-3 mb-4" id="img" style="width: 25rem;" >

Modify your src. You have not set it up correctly. If you are working with JavaScript, this is client-side and should be done this way.

<img class="img-fluid px-3 px-sm-4 mt-3 mb-4" id="img" style="width: 25rem;" alt="learning" src="images/download.jpg">

You did not mention what you are doing on localhost or not because you may need to Absolute URL

All you have to do is to fix the Relative URL . Using ~ in URL doesn't make a valid URL.

  • If the images directory is at the root of your web application then use "/images/Capture205450514.PNG"
  • If the images directory is at the same level as of your HTML page then use "./images/Capture205450514.PNG" or simply "images/Capture205450514.PNG"
  • If the images directory is at one level higher than your HTML page then use "../images/Capture205450514.PNG"

Click here for reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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