简体   繁体   中英

JavaScript - Clicking on an image

I am programming a browser game in JavaScript and need to create a Card Class. This class has (with other variables) an image, which should be displayed when I create an object. How do I display the object's image and call a function when the image is clicked?

With this code I can display the image wherever I want, but the OnClick function is called instantly when I open the .htm file instead of when I click in the image.

<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>

Please, some help with detecting when I click on the image and displaying the image in a less dirty way (if it's possible)?

Thanks in advance!

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);

Made some changes to your code. Hope it helps!

<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>

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