简体   繁体   English

如何使用 HTML 输入为 JavaScript class 供电

[英]How to use HTML input to feed a JavaScript class

First off, I'm new to JS and learning.首先,我是 JS 和学习的新手。 Hence the probably basic question.因此,可能是基本问题。

I've made a sliding puzzle based of a tutorial online.我根据在线教程制作了一个滑动拼图。 I get most of it, but now I'm trying to make it more universal.我得到了大部分,但现在我正试图让它更普遍。 As in, I want to allow a user to enter a url of an image and the preferred dimensions for the puzzle (eg 3x3 or 4x4 etc) and then have the JS run to make the puzzle with the desired specifications.例如,我想让用户输入图像的 url 和拼图的首选尺寸(例如 3x3 或 4x4 等),然后让 JS 运行以制作具有所需规格的拼图。

Below I've added some HTML and JS that is working.下面我添加了一些 HTML 和 JS 正在工作。 I added default values and the code runs fine.我添加了默认值,代码运行良好。 However, I can't seem to make it that an event listener (eg onclick) triggers the "new PicturePuzzle" with the url and dimensions that are entered in the html input fields at the moment of the click.但是,我似乎无法使事件侦听器(例如 onclick)在单击时触发带有 url 和在 html 输入字段中输入的尺寸的“新图片拼图”。

HTML: HTML:

    <p>
        <p>Paste the url of the image you want to use.</p>
        <input type="text" name="url" id="urlInput"
         value="https://live.staticflickr.com/933/43267995794_655733e7c6_b.jpg" required />
    </p>

    <p>
        <p>Select the dimensions you want the puzzle to be in.</p>
        <input type="number" name="dimension" id="dimensionInput" value="3" required/>
    </p>

    <div id="canvas"></div>

JS file one (this is the complete js file): js文件一(这是完整的js文件):

import PicturePuzzle from './PicturePuzzle.js';

let picturePuzzle = new PicturePuzzle(
    document.getElementById('canvas'),
    document.getElementById('urlInput').value,
    600,
    document.getElementById('dimensionInput').value
);

JS file two (PicturePuzzle.js), which extends further after the dots. JS 文件二 (PicturePuzzle.js),它在点之后进一步扩展。 This contains the actual code for the puzzle:这包含拼图的实际代码:

export default class PicturePuzzle {
    constructor(canvas, imageSrc, width, dimension) { ....

You could try wrapping the part where you create an instance of the PicturePuzzle class in a function and call that from an event-listener.您可以尝试将创建 PicturePuzzle class 实例的部分包装在 function 中,然后从事件侦听器中调用它。

Assuming you have a button to start the whole process with the id "btn", you could do that as follows:假设你有一个按钮来启动整个过程,id 为“btn”,你可以这样做:

const canvas = document.getElementById('canvas');
const urlInput = document.getElementById('urlInput');
const dimensionInput = document.getElementById('dimensionInput');
const btn = document.getElementById('btn')

btn.onclick = createPuzzle; 

function createPuzzle() {
   return new PicturePuzzle(
      canvas,
      urlInput.value,
      600,
      dimensionInput.value
   );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM