简体   繁体   中英

Img src url with variables

I would like to load an image with the page load using javascript and html. Here was my original code that worked perfectly in IE11 and Firefox on Windows 10 but not in IE11 on Windows7. Is it the syntax/quotes that it doesn't like?

var1 = "someURl";
var2 = "someEndingToURl";
var mainImgsrc = var1 + 'some_text' + var2;

document.addEventListener('DOMContentLoaded', function () {
document.getElementById('IMG1').src= mainImgsrc

<img id="IMG1" src="" width="1000px" height="700px" name="mymap" align="middle" alt="Map" ;/>

It works fine here. Do you have a link to the site you are using? Perhaps the lack of var in front of var1 and var2 means you are unintentionally overwriting a global variable? You can fix that by adding var and moving those inside of your DOMContentLoaded listener (to avoid them being implicit globals):

 document.addEventListener('DOMContentLoaded', function() { var var1 = "https://makelin.us/"; var var2 = "/70"; var mainImgsrc = var1 + '100' + var2; document.getElementById('IMG1').src = mainImgsrc; }); 
 <img id="IMG1" src="" width="100" height="70" name="mymap" align="middle" alt="Map" ;/> 

Have you tried the basic method...

<body onload="IMG1.src= mainImgsrc;">

The onload event is supported by all popular engines including Trident.

Make sure that your DOM is fully loaded before trying to change an image SRC. Have you tried to console.log() your document.getElementById ? BTW, your code is not properly written, you miss }); after your SRC assignment.

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