所以,我有一个函数,我在其中循环10次,以创建10个元素。我要完成的工作是:我想给这些div
元素分配不同的id
,以便在需要时可以分别访问它们。
function addDay() {
for(k = 0; k < 10; k++){
let div = document.createElement("div");
div.style.background = "red"
div.style.color = "white"
div.style.width = "40px"
div.style.height = "20px"
div.style.margin = "0.5px"
div.style.textAlign = "center"
div.style.borderRadius = "6px"
div.setAttribute("class", "studentGrades");
div.setAttribute("id", "sgId")
div.setAttribute("onclick", "averageFunc(this, Number(prompt('Please, enter number here')))");
div.innerHTML = "0"
document.querySelector("#container3").appendChild(div)
}
}
所以我想得到类似的东西,
div id="sgId1"
div id="sgId2"
div id="sgId3"
,等等。注意:我只是从编码本身开始,目前是Vanilla JS的第3周。所以我不能使用任何库/框架
答案 0 :(得分:0)
在循环中使用k值指定每个元素。
div.setAttribute("id","sgId"+k);
答案 1 :(得分:0)
使用此表达式:
div.id = "sgId" + (k + 1);
var total = 0;
var c101 = document.querySelector("#class101");
var gradeAvg = document.querySelector("#gradeAvg");
var list = document.createElement("ol");
for (let k = 0; k < 10; k++) {
var li = document.createElement("li");
li.classList.add("grade");
li.id = "sgId" + (k + 1);
li.textContent = "0";
li.addEventListener('click', enterGrade);
list.appendChild(li);
}
c101.appendChild(list);
function enterGrade(e) {
var num = Number(prompt(`Please, enter number here`));
e.target.textContent = num;
var total = avg(num);
gradeAvg.textContent = total;
}
function avg(num) {
var sum = total += num;
return sum / 10;
}
.grade {
background: red;
color: white;
width: 40px;
height: 20px;
margin: 0.5px;
text-align: center;
border-radius: 6px;
}
<h4>Student Grades</h4>
<section id='class101'></section>
<label>Grade Average: </label><output id='gradeAvg'></output>