2014-09-28 19 views
-3

我有一個地方爲主照片(id =「main」)和表中的其他照片(id =「pic + 1(2,3,4,5,6) )「)。我想點擊一張id =「pic n」的照片,並將其加載到ID爲「main」的元素中。如何實現這一點?使用javascript在特定元素中加載圖像

另外我有一個錯誤

Uncaught TypeError: Cannot set property 'onclick' of null.

這裏是我的代碼:

<img id="main" src=""> 

galery(dir){ 
... 

... 
    function createPreview() { 
     var f = document.createElement("table"); 
     var row = f.insertRow(); 
     for(var j = 0; j < count ; j++) { 
      var cell = row.insertCell(j); 
      var img = new Image(); 
      img.src = dir + '/' + j + ".jpg"; 
      img.width = "100"; 
      img.id = 'pic' + j; 
      cell.appendChild(img); 
     } 
     document.body.appendChild(f); 
    } 

    document.getElementById(this.pic).onclick = function() { 
     document.getElementById('main').src = this.src; 
    } 


... 
} 
+0

尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須包含所需的行爲,特定的問題或錯誤以及在問題本身中重現問題所需的最短代碼。沒有明確問題陳述的問題對其他讀者無益。 – 2014-09-28 08:39:28

+2

'this.pic'顯然不是你想象的那樣。 – adeneo 2014-09-28 08:41:03

+0

幫幫我!我不知道該怎麼做。 – NEW 2014-09-28 08:42:03

回答

0

雖然你的代碼有JS如何在這裏工作的許多錯誤和誤解是一些簡單的代碼,解決了這個問題

//fake an image directory 
    var count = 3; 
    var dir = 'http://lorempixel.com/300/300/abstract/' 

    //setup a table 
    var f = document.createElement("table"); 
    var row = f.insertRow(); 
    for (var j = 0; j < count; j++) { 
     var cell = row.insertCell(j); 
     imagepath = dir + j; 
     cell.innerHTML = '<img src="' + imagepath + '" width="100" onclick="showmain(' + j + ')">'; 
    } 
    document.body.appendChild(f); 

    //change imagesrc in main tag 
    function showmain(image) { 
     document.getElementById('main').src = dir + image; 
    } 

這是你用JavaScript做最基本的(小白)的事情。

我強烈建議您在回來之前閱讀這些基本問題之前再閱讀一些教程。

這裏是一個Plunker

沒有onload處理程序,所以腳本在頁面的末尾。

+0

我有一個錯誤 - 未捕獲的ReferenceError:showmain沒有定義,因爲我的主要功能是函數galery(dir){}我的帖子中的代碼存在於galery(dir)中。如何在這個函數中調用showmain? – NEW 2014-09-28 09:59:30

+0

我更新了我的帖子。 – NEW 2014-09-28 10:00:28

+0

Doh,只要在任何函數或onload處理程序之外保持showmain。最好的地方是在你的腳本標籤的末尾,就在你做之前。或者如果想絕對確定添加另一個腳本部分。你可以擁有儘可能多的你想要的。 – mainguy 2014-09-28 10:22:29

0

您在代碼中有很多錯誤的:

1)可以定義裏面的VAR˚F函數,所以它的範圍在函數內部。但是,然後你試圖通過document.body.appendChild(f);這個功能不能正常工作。您應該在功能內移動document.body.appendChild(f);

2)然後你得到Uncaught TypeError: Cannot set property 'onclick' of null.,因爲document.getElementById(this.pic)返回null。 this.pic不返回標識。

3)關閉您的img tag

4)你有2個額外的}

而且我相信有更多,如果你告訴我們,所有的代碼。

+0

如何關閉img標籤? – NEW 2014-09-28 09:21:04

+0

如何調用單擊的函數圖像? – NEW 2014-09-28 09:21:53

+0

'' – 2014-09-28 09:22:54