gpt4 book ai didi

javascript - 为什么我无法获得输入值

转载 作者:行者123 更新时间:2023-11-30 20:59:23 24 4
gpt4 key购买 nike

单击后我无法获取输入值以在页面上创建矩形。我认为这是因为事件循环,并试图将其包装在 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>

最佳答案

(() => {
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;
}
})()
body {
height: 1000px;
width:100%;
}
<form id = "form">
<input type="text" placeholder="height">
<input type="text" placeholder="width">
</form>

setTimeout 不会返回值给你。

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

关于javascript - 为什么我无法获得输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47286889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com