Estaba tratando de crear una función Javascript en HTML, que debería crear un rectángulo y establecer el tamaño según los gustos del usuario con este código:
class Rectangle{ constructor(height, width){ this.height = height; this.width = width; function createRectangle(Rectangle){ var input1 = document.getElementbyId("1stinput").value; var input2 = document.getElementbyId("#2ndinput").value; var input1int = parseFloat(input1); var input2int = parseFloat(input2); var Rectangle1 = new Rectangle(this.height=input1int, this.width=input2int);}; document.querySelector("Rectangle").setAttribute('width', parseFloat(Rectangle1.width)); document.querySelector("Rectangle").setAttribute('height', parseFloat(Rectangle1.height)); }; }; </script> <input type="text" name="" value="" id="1stinput"> <input type="text" name="" value="" id="2ndinput"> <button onclick=Rectangle.createRectangle(Rectangle)>create</button> <svg width=0 height=0> <rect width=0 height=0 style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" id="Rectangle"/> </svg>Pero eso no funcionó, recibí este error:
Uncaught TypeError: Rectangle.createRectangle is not a function at HTMLButtonElement.onclickAsí que creo que createRectangle debería ser un método, pero no sé cómo implementar métodos en el botón, ¿alguien puede ayudarme? Sería muy bueno, gracias!!!
Es posible que desee revisar cómo está abordando esto. Las clases tienen métodos, por lo que no puede simplemente agregarles una función ( aquí está la documentación ). Además, tal vez mantenga las manipulaciones DOM fuera de la clase en sí, y simplemente deje que devuelva una cadena HTML basada en los valores de entrada. Luego puede agregar eso a un elemento DOM de su elección.
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } createRectangle() { return ` <svg> <rect width="${this.width}px" height="${this.height}px"></rect> </svg> `; } } const input1 = document.querySelector('#input1'); const input2 = document.querySelector('#input2'); const button = document.querySelector('button'); const output = document.querySelector('#output'); button.addEventListener('click', handleClick, false); function handleClick() { const n1 = parseFloat(input1.value); const n2 = parseFloat(input2.value); const rectangle = new Rectangle(n1, n2); output.innerHTML = rectangle.createRectangle(); } svg { width: 100%; } rect { fill: rgb(0, 0, 255); stroke-width: 3; stroke: rgb(0, 0, 0);} #output { margin-top: 1em; } <input type="text" id="input1"> <input type="text" id="input2"> <button>create</button> <div id="output"></div>Documentación adicional