我的代码中有一个文本框和一个按钮。我想让用户输入文本并单击按钮。如果是这样,将使用用户输入的文本创建卡片,卡片的背景颜色将使用 json 文件设置。 但是在我的代码中,如果用户第二次点击按钮,之前创建的卡片就会消失,并且正在创建一张新卡片,留下之前创建的卡片的空间。但我希望所有卡片都一张一张地对齐。 我认为这可以通过为每张卡设置不同的 id 使用循环函数来完成。不幸的是我无法正确地做到这一点。 我在这里附上我的代码,请有人帮助我。
index.html
<!DOCTYPE html>
<html>
<head>
<title>Task</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel = "stylesheet" href = "css/style.css" type = "text/css">
</head>
<body>
<h2>Creative Handle Task Assignment</h2>
<input type="text" name="text" id="text" placeholder="Enter your text here...">
<button id="btn">Click</button>
<div class="flex-container" id="container">
</div>
<script src="js/custom_script.js" type="text/javascript"></script>
</body>
</html>
样式.css
.flex-container {
display: flex;
flex-direction: column-reverse;
justify-content: center;
align-items: center;
}
.flex-container > div {
/*background-color: DodgerBlue;*/
color: white;
width: 100px;
margin: 10px;
text-align: center;
line-height: 75px;
font-size: 30px;
}
custom_script.js
const subBtn = document.getElementById("btn");
const inptTxt = document.getElementById("text");
const contDiv = document.getElementById("container");
subBtn.disabled = true
inptTxt.addEventListener('input', evt => {
const value = inptTxt.value.trim()
if (value) {
inptTxt.dataset.state = 'valid'
subBtn.disabled = false
} else {
inptTxt.dataset.state = 'invalid'
subBtn.disabled = true
}
})
var xhttp = new XMLHttpRequest();
subBtn.addEventListener("click",function(){
var crd = document.createElement("div");
crd.setAttribute("id", "card");
crd.innerHTML = inptTxt.value;
contDiv .appendChild(crd);
xhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("card").style.background = JSON.parse(this.responseText).color;
}
};
xhttp.open("GET","http://api.creativehandles.com/getRandomColor","" ,true);
xhttp.send();
})
最佳答案
每次您创建一个新元素时,您都会为它指定 card
的 ID。不能有多个具有相同 id 的 html 元素。您应该改用 crd.setAttribute("class", "card");'
。您加载的外部样式表具有类 .card
的样式,但没有 id #card
的样式。
关于javascript - 如何在 Javascript 的 for 循环中创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59477999/