[英]How to create element within for loop in Javascript
我的代碼中有一個文本框和一個按鈕。 我想讓用戶輸入文本並單擊按鈕。 如果是這樣,將使用用戶輸入的文本創建一張卡片,並使用 json 文件設置卡片的背景顏色。 但是在我的代碼中,如果用戶第二次單擊該按鈕,則先前創建的卡片將消失,並且正在創建新卡片,從而留下先前創建的卡片的空間。 但我希望所有的卡片都對齊一張低一張。 我認為這可以通過為每張卡設置不同的 id 使用循環函數來完成。 不幸的是,我無法正確地做到這一點。 我在這里附上我的代碼,請有人幫我解決這個問題。
索引.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>
樣式文件
.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
。
您不能為多個 html 標簽提供 id。 而不是 id 使用類屬性即
crd.setAttribute("class", "card");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.