2013-06-11 53 views
0

我对JavaScript很新,我正在制作一个HTML网站。Javascript:我如何制作一个Javascript图像链接到一个页面?

因为我是Javascript新手,我不知道如何显示图像,并且当图像被点击时,它会链接到一个页面。

我知道如何在HTML中做到这一点,但由于我的免费主机,如果我不是对有多少图像(我会做很多)进行单一更改,或者它链接到(这将显示在每页)我需要通过每一页。

我需要的是在同一个标​​签上打开页面。

+0

如果你有一些代码显示它 –

+0

什么最小的HTML你有(足以证明你的问题 - 网页),以及你要添加的JavaScript新的HTML什么事件?你想添加什么*精确* html? –

+0

链接关于是标签,而不是图像本身。这是很好的形式。 –

回答

5

试试这个:

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

如果没有更多信息,我将提供此作为一种相对跨浏览器的方法,该方法将附加包装在a元素中的img元素。这适用于以下(简单)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> 

而且下面的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

相关问题