为什么这有效:
const details = document.querySelector('details')
document.getElementById("details1").addEventListener("toggle", event => {
if (details1.open) {
changeText1("open");
} else {
changeText1("closed");
}
});
document.getElementById("details2").addEventListener("toggle", event => {
if (details2.open) {
changeText2("open");
} else {
changeText2("closed");
};
});
function changeText1(status) {
if(status == "open") {
document.getElementById("p1").innerText = "opened";
} else if (status == "closed") {
document.getElementById("p1").innerText = "closed";
}
}
function changeText2(status) {
if(status == "open") {
document.getElementById("p2").innerText = "opened";
} else if (status == "closed") {
document.getElementById("p2").innerText = "closed";
}
}
<html>
<body>
<details id="details1">
<summary>#1</summary>text
</details>
<details id="details2">
<summary>#2</summary>text
</details>
<p id="p1">not opened or closed</p>
<p id="p2">not opened or closed</p>
</body>
</html>
这是行不通的吗:
const details = document.querySelector('details')
function changeText(detailnr, status) {
let pnr = "p" + detailnr;
if(status == "open") {
document.getElementById(pnr).innerText = "opened";
} else {
document.getElementById(pnr).innerText = "closed";
}
}
function maaklistner(detailsnr){
let detailsid = "details" + detailsnr;
document.getElementById(detailsid).addEventListener("toggle", event => {
if (detailsid.open) {
changeText(detailsnr, "open");
} else {
changeText(detailsnr, "closed");
}
});
}
for(let i = 1; i < 3; i++){
maaklistner(i);
}
<html>
<body>
<details id="details1">
<summary>#1</summary>text
</details>
<details id="details2">
<summary>#2</summary>text
</details>
<p id="p1">not opened or closed</p>
<p id="p2">not opened or closed</p>
</body>
</html>
虽然代码本质上是完全重复的......
似乎事件侦听器本身已创建。但是,在 seconde 代码中没有正确处理 details.opened 语句,而在第一个代码中确实可以使用相同的方法。
有没有办法让第二种方法起作用?因为我需要创建超过 2000 个...