简体   繁体   中英

Javascript: How do I make a Javascript image link to a page?

I am very new to Javascript, I am making a HTML website.

Since I am new to Javascript, I do not know how to show an image, and when the image is clicked make it link to a page.

I know how to do it in HTML, but due to my free host if I wasn't to make a single change to how many images there are (which I will do a lot), or where it links to (which will be shown on every page) I will need to go through every page.

All I need it to do is open the page on the same tab.

Try this:

var img = new Image();
img.src = 'image.png';
img.onclick = function() {
    window.location.href = 'http://putyourlocationhere/';
};
document.body.appendChild(img);

Without more information, I'm going to offer this as a relatively cross-browser approach, which will append an img element wrapped in an a element. This works with the following (simple) HTML:

<form action="#" method="post">
    <label for="imgURL">image URL:</label>
    <input type="url" id="imgURL" />
    <label for="pageURL">page URL:</label>
    <input type="url" id="pageURL" />
    <button id="imgAdd">add image</button>
</form>

And the following JavaScript:

// a simple check to *try* and ensure valid URIs are used:
function protocolCheck(link) {
    var proto = ['http:', 'https:'];

    for (var i = 0, len = proto.length; i < len; i++) {
        // if the link begins with a valid protocol, return the link
        if (link.indexOf(proto[i]) === 0) {
            return link;
        }
    }

    // otherwise assume it doesn't, prepend a valid protocol, and return that:
    return document.location.protocol + '//' + link;
}

function createImage(e) {
    // stop the default event from happening:
    e.preventDefault();
    var parent = this.parentNode;

    /* checking the protocol (calling the previous function),
       of the URIs provided in the text input elements: */
    src = protocolCheck(document.getElementById('imgURL').value);
    href = protocolCheck(document.getElementById('pageURL').value);

    // creating an 'img' element, and an 'a' element
    var img = document.createElement('img'),
        a = document.createElement('a');

    // setting the src attribute to the (hopefully) valid URI from above
    img.src = src;

    // setting the href attribute to the (hopefully) valid URI from above
    a.href = href;
    // appending the 'img' to the 'a'
    a.appendChild(img);
    // inserting the 'a' element *after* the 'form' element
    parent.parentNode.insertBefore(a, parent.nextSibling);
}

var addButton = document.getElementById('imgAdd');

addButton.onclick = createImage;

JS Fiddle demo .

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