简体   繁体   中英

Call js method in html

I have a problem with class in js and how to call it in html file.

 class SetProp(){ constructor(height,width){ this.height = height; this.width = width; } function getHeight(){ return this.height; } function getWidth(){ return this.width; } } 
 <!DOCTYPE html> <html> <head> <title>Hello</title> <script src="TryClass.js" type="text/javascript"> prop = new SetProp(1000,1000); </script> </head> <body> <h1>Hello</h1> <canvas id="canvas" width="prop.getWidth() " height="prop.getHeight();" style="border:1px solid #000000"></canvas> </body> </html> 

I want to make canvas with 1000*1000 by using this method. And need to pratices about using class.

The html properties width and height cannot be assigned to functions, what you need to do is write a function that will return the width and height on button click or after DOM load modify the attributes of your element with Javascript using Selectors as shown below:

document.getElementById('canvas').style.width =prop.getWidth() ;
document.getElementById('canvas').style.height =prop.getHeight() ;

your getHeight() and getWidth() functions are private and dont asign to main class prototype so if you want access them you should use main class prototype like this:

'class SetProp(height,width){
    this.height = height;
    this.width = width;

}
 SetProp.prototype.getHeight=function(){
       return this.height;
  }
  SetProp.prototype.getWidth=function(){
       return this.width;
  }'

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