简体   繁体   中英

Display image with link in HTML using external Javascript?

I am new to javascript and I am trying to display different images that have links in HTML using an external Javascript file. I'm not entirely sure this is possible or the best way to go about it. I've created the following scripts, which I intend on putting in the same external file.

var img1 = new Image();
img1.src = 'myimage.jpg';
img1.onclick = function() {
    window.location.href = 'mylink.html';
}; 
document.body.appendChild(img1);

and

var img2 = new Image();
img2.src = 'myimage.jpg';
img2.onclick = function() {
    window.location.href = 'mylink.html';
}; 
document.body.appendChild(img2);

I can call the entire sheet, but not the individual scripts using the code below, so I want to know if it's possible to call the individual scripts from the same sheet? I would like to avoid creating multiple .js files.

<script src="js/myjavascript.js"></script>

Create some functions in your JavaScript file

function addImage1() {
  // some code
}

function addImage2() {
 // some more code
}

Then include the JavaScript file as normal and then call the functions when you want to add the images :

<script>
addImage1();
addImage2();
</script>
var a = document.createElement("a");  // <- <a> element (link)
a.href = "myfile.html";  // <- set link (href)
var myimage = document.createElement("image");  // <- image
myimage.src = "myimage.png";  // <- image source
a.appendChild(myimage);  // <- append image to <a> tag
document.body.appendChild(a);  // <- append <a> tag to body

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