如何只使用JavaScript创建DIV onclick


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-A-Sketch</title>
</head>
<body>
<h1>Etch-A-Sketch</h1>
<p id="Grid-Size">Grid Size</p> 
<form onsubmit="getTotalGridSize()"> <!--onsubmit has to be on the form tag not the submit input-->
<input type="number" placeholder="size" min="1" max="100" id ="size" value="" oninput="getSizeValue()">
<input type="submit" id="Submit" value="Submit" onclick="createTile()">
</form>
<p id="Colors">Choose Color</p> 
<form id="color-options" >
<input type="radio" name="choice" value="blue">
<label for="default">Default</label>
<input type="radio" name="choice" value="random"  >
<label for="random">Random</label>
<input type="radio" name="choice" value="white" >
<label for="white">White</label>
<input type="radio" name="choice" value="user" >
<label for="color-picker">Color Picker</label>
<input type="color" id="color-picker" value=""> 
</form>
<div id="Sketch">
<div id="tile" onmouseover="updateHoverColor()">
</div>
</div>
<script src="etch.js" charset="utf-8"></script>
</body>
</html>

//Dom Accessed Variables
let tile = document.getElementById("tile")
let sizeValue = null
let gridSize= null 
let containerDiv = document.getElementById("sketch")
//input functions 
function getSizeValue() {
sizeValue = document.getElementById('size').value //getting the inputs value
}
function getTotalGridSize() {
gridSize = sizeValue * sizeValue
}
//Generates random RGB values
function randomColor() {
let red = Math.floor(Math.random() * 255 + 1);
let blue = Math.floor(Math.random() * 255 + 1);
let green = Math.floor(Math.random() * 255 + 1);
//Returns string with style to be applied
let random = `rgb(${red}, ${green}, ${blue})`;
tile.style.backgroundColor = random;
}
function updateHoverColor() {
let colorChoice = document.getElementById("color-picker").value
if(document.querySelector('#color-options > input:checked').value === "blue") {
tile.style.backgroundColor = "blue"
} else if (document.querySelector('#color-options > input:checked').value === "random") {
randomColor()
} else if (document.querySelector('#color-options > input:checked').value === "white") {
tile.style.backgroundColor = "white"
} else if (document.querySelector('#color-options > input:checked').value === "user") {
tile.style.backgroundColor = colorChoice;
}
}
function createTile() {
let baby = document.createElement("div");
baby.style.height = "200px"
baby.style.width = "100px"
baby.style.backgroundColor = "black"
document.body.appendChild(baby)
}

我要做的是在用户单击提交按钮后,在容器div中创建另一个div。我使用JavaScript创建了一个函数,然后将其附加到同一按钮上的onclick。我甚至使用完全相同的语法从W3schools创建函数来创建和附加and元素,但它在我的代码中似乎根本不起作用,我正在努力找出原因。

第一个表单中的提交按钮有一个onclick包含的表单也有onsubmit。这将导致在什么功能以及何时启动方面出现一些不一致的行为。坚持使用onsubmit表格。我还建议不要用HTML附加事件监听器,而是给表单一个ID,然后通过ID附加事件监听器。

// HTML
<form id="totalGridSizeForm">
// JavaScript
const gridSizeForm = document.getElementById("totalGridSizeForm");
gridSizeForm.addEventListener("submit", (event) => {
event.preventDefault();
// Whatever logic you need goes here
});

应用程序的主要问题是,当您提交一些表单、发送信息和刷新页面时,您的div可能正在创建中,但后来由于页面重新加载而被删除。

最好的选择是将某些条件保存在LocalStorage中,每次刷新后,如果页面满足特殊条件,就会显示div。以下是示例:

function saveInformation(func) {
var funcs = [
'size',
'save'
] 

if (func==funcs[0]) {
sizeValue = document.getElementById('size').value;
}
if (func==funcs[1]) {
localStorage.setItem('saveCheck','true');
}
return false;
}
function check() {
var saveCheck = localStorage.getItem('saveCheck');
if (saveCheck == 'true') {
generateDIV();
} 
}
function generateDIV() {
let element = document.createElement("div");
element.style.height = "200px";
element.style.width = "100px";
element.style.backgroundColor = "black";
document.body.appendChild(element);
}
document.addEventListener('DOMContentLoaded',function() {
check();
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/html/b.js"></script>
<title>Document</title>
</head>
<body>
<form>
<input type='number' placeholder='Number' id='size'>
<input type='submit' onclick='saveInformation("size");saveInformation("save");'>
</form>
</body>
</html>

编辑:我无法从堆栈溢出代码片段保存到本地存储,所以您需要从编辑器中测试此代码

我所做的是,我用"return false"禁用了提交按钮,但我们仍然从输入值中获取信息,只是没有重新加载和显示的div。

所以,我们的想法是有一个函数来保存输入值中的信息,并将名为"saveCheck"的bool保存到本地存储中。如果本地存储中给定的"saveCheck"为true,我们将调用"generateDIV((",并在每次刷新页面时加载该div。

这是一个纯Javascript的例子,但我建议您在还没有使用JQuery的情况下开始使用。

希望我能帮上忙!

最新更新