2013-03-27 159 views
2

我使用JavaScript編寫瀏覽器遊戲,需要創建一個卡片類。 這個類有(與其他變量)一個圖像,當我創建一個對象時應該顯示這個圖像。如何在點擊圖像時顯示對象的圖像並調用函數?JavaScript - 點擊圖片

使用此代碼,我可以在任何需要的位置顯示圖像,但是當打開.htm文件而不是在圖像中單擊時,會立即調用OnClick函數。

<html> 
<head> </head> 
<body> 
<script type="text/javascript">  
    function Card(photo){ // this is my object 
     this.randomVariable=42; 
     this.pic = new Image(); // creating an Image object inside my Card class. 
     this.pic.src=photo; 
     this.pic.height = 300; 
     this.pic.width = 200; 
     this.pic.style.position="absolute"; // this 3 lines should set the image's position, and it does. 
     this.pic.style.top = 50 + "px"; 
     this.pic.style.left = 50 + "px"; 
     this.OnClick = document.write("lala"); 
    } 

    var myObject = new Card("cardback.jpg"); 
    myObject = document.body.appendChild(coso1.pic); // is this how I should create the image? It appears where I want, but it doesn't seem a "clean" programming. 
    myObject.OnClick = document.write("lala" + coso1.pic.offsetLeft + coso1.pic.offsetTop); // this is casted when I open the file, and not when I click on the image. *sadface* 

</script> 
</body> 
</html> 

請幫助我檢測一下當我點擊圖像並以不太髒的方式顯示圖像(如果可能的話)?

在此先感謝!

回答

0

http://jsfiddle.net/CTWWk/1/

var image = new Image(); 
image.src = 'https://www.google.co.il/images/srpr/logo4w.png'; 

image.onclick = function(){ 
     alert('I Clicked an image now !'); 
}; 

var divy = document.getElementById('divy'); 
divy.appendChild(image); 
+0

爲什麼當我把你的代碼放入html內容時圖像不顯示? CookieGuy 2013-03-28 00:34:24

+0

我只是增加了一些元素的id =「divy」 - 看我發佈的鏈接 - 這是完整的源代碼[http://jsfiddle.net/CTWWk/1/](http:// jsfiddle.net/CTWWk/1/) – Adidi 2013-03-28 00:43:54

+0

它不能在普通的JavaScript中運行?這段時間我可能會很煩,但重要的是我可以理解,以後再做更大的事情。提前致謝。 – CookieGuy 2013-03-28 14:34:43

0

做了一些改動你的代碼。希望能幫助到你!

<html> 
<head> </head> 
<body> 
<script type="text/javascript">  
    function Card(photo){ 
    var cardInstance = new Image(); 
    cardInstance.src = photo; 
    cardInstance.addEventListener('click', function (e) { 
      alert(1); 
     }); 
    return cardInstance; 
    } 

    var myObject = new Card("cardback.jpg"); 
    document.body.appendChild(myObject); 

</script> 
</body> 
</html> 
+0

謝謝!很多!! – CookieGuy 2013-03-28 00:51:11

+0

什麼是「return cardInstance」;對於?我如何做到這一點,如果我想在我的課堂上有多個圖像並單獨顯示它們,併爲每個圖像分別顯示不同的eventListener? – CookieGuy 2013-03-28 14:36:28