gpt4 book ai didi

javascript - 具有相同功能的 DOM 多个 ID

转载 作者:行者123 更新时间:2023-11-28 05:11:27 24 4
gpt4 key购买 nike

如何让ID使用相同的功能?。我打算制作更多具有相同功能的元素,但不想制作更多功能。

 var star_1 = document.getElementById("star1");
var star_2 = document.getElementById("star2");

var toggle = false;

favToggle = function() {


if (toggle === true) {
star_1.src = "assets/svg/checked-star.svg";

} else {
star_1.src = "assets/svg/unchecked-star.svg";
}

toggle = !toggle;
}

favToggle1 = function() {


if (toggle === true) {
star_2.src = "assets/svg/checked-star.svg";

} else {
star_2.src = "assets/svg/unchecked-star.svg";
}

toggle = !toggle;
}

star_1.addEventListener("click", favToggle);
star_2.addEventListener("click", favToggle1);

最佳答案

// Number of stars you have
const nbStars = 4;

// An array where we keep the toggle state of each star
const toggles = [];

// Deal with the stars. One by one
for (let i = 0; i < nbStars; i += 1) {
// Setup the initial state of the toggle
toggles.push(false);

const star = document.getElementById(`star${i + 1}`);

star.addEventListener('click', () => {
if (toggles[i] === true) {
star.innerHTML = 'assets/svg/checked-star.svg';
} else {
star.innerHTML = 'assets/svg/unchecked-star.svg';
}

// Change the state of the toggle for that particular star
toggles[i] = !toggles[i];
});
}
.star {
height: 5em;
width 5em;
background-color: #444444;
margin: 1em;
color: white;
}
<div id="star1" class="star"></div>
<div id="star2" class="star"></div>
<div id="star3" class="star"></div>
<div id="star4" class="star"></div>


关于 querySelectorAll 的另一种使用 @brk 的好主意

const toggles = Array.from(document.querySelectorAll('[id^="star"]')).map((x, xi) => {
x.addEventListener('click', () => {
if (toggles[xi] === true) {
x.innerHTML = 'assets/svg/checked-star.svg';
} else {
x.innerHTML = 'assets/svg/unchecked-star.svg';
}

// Change the state of the toggle for that particular star
toggles[xi] = !toggles[xi];
});

// Setup the initial state of the toggle
return false;
});
.star {
height: 5em;
width 5em;
background-color: #444444;
margin: 1em;
color: white;
}
<div id="star1" class="star"></div>
<div id="star2" class="star"></div>
<div id="star3" class="star"></div>
<div id="star4" class="star"></div>

关于javascript - 具有相同功能的 DOM 多个 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55105312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com