2013-06-11 24 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

相關問題