为什么我无法获得输入的价值

时间:2017-11-14 13:18:29

标签: javascript

点击后,我无法获得在页面上创建矩形的输入值。我认为这是因为事件循环并尝试将其包装在setTimeout()中,但它无法解决。那么我应该怎么做以及它实际上如何运作? 代码:

(() => {
    const inputElements = document.getElementsByTagName("INPUT");
    const inputs = {
        height: setTimeout(() => {return inputElements[0].value},0),
        width: inputElements[1].value || 50 
    }

    const elements = [];
    const bodyClick = document.body.addEventListener('click', () => {
        event.target.tagName !== "INPUT" ? addRectangle(): formClick();
    })
    const addRectangle = () => {
        let newRectangle = document.createElement('div');
        newRectangle.style.background = getRandomColor();
        newRectangle.style.width = inputs.width + 'px';
        console.log(inputs.width)
        newRectangle.style.height = inputs.height +'px';
        document.body.appendChild(newRectangle);
        elements.push(newRectangle);
    }
    const formClick = () => {

    }
    const getRandomColor = () => {
        let letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
})()
body {
    height: 1000px;
    width:100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="style.css" rel="stylesheet">
    <title>Lab 6</title>
</head>
<body>
    <form id = "form">
        <input type="text" placeholder="height">
        <input type="text" placeholder="width">
    </form>
<script src="source.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
(() => {
    const inputElements = document.getElementsByTagName("INPUT");
    const elements = [];
    const bodyClick = document.body.addEventListener('click', () => {
        event.target.tagName !== "INPUT" ? addRectangle(): formClick();
    })
    const addRectangle = () => {
        const inputs = {
          height: inputElements[0].value || 50,
          width: inputElements[1].value || 50 
        }
        let newRectangle = document.createElement('div');
        newRectangle.style.background = getRandomColor();
        newRectangle.style.width = inputs.width + 'px';
        newRectangle.style.height = inputs.height +'px';
        document.body.appendChild(newRectangle);
        elements.push(newRectangle);
    }
    const formClick = () => {

    }
    const getRandomColor = () => {
        let letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
})()
&#13;
body {
    height: 1000px;
    width:100%;
}
&#13;
<form id = "form">
    <input type="text" placeholder="height">
    <input type="text" placeholder="width">
</form>
&#13;
&#13;
&#13;

setTimeout不会给你带来价值。

单击正文后获取输入值,然后将其设置为创建的div。