我想交换一个类,与另一个类交换,但要有一个循环。当你点击如果棕色方 block 他移动到蓝色方 block 上,蓝色方 block 现在在棕色方 block 的位置上
还有更多他可以无限移动。我希望你理解这个问题,我发布了我的代码的开头
var braken = document.querySelector(".board li.braken");
var champagne = document.querySelector(".board li.champagne");
braken.addEventListener("click", function () {
braken.classList.remove("braken")
braken.classList.add("champagne");
})
champagne.addEventListener("click", function () {
champagne.classList.remove("champagne")
champagne.classList.add("braken")
})
最佳答案
使用 querySelectorAll
和一个 forEach
循环和 classList.toggle
var things = document.querySelectorAll(".board li.champagne,.board li.braken");
[].forEach.call(things, function(thing) {
thing.addEventListener('click', function() {
thing.classList.toggle('champagne');
thing.classList.toggle('braken');
});
});
Note, eventually once all browsers have caught up, or with the right polyfill - you can do
document.querySelectorAll(".board li.champagne,.board li.braken")
.forEach(function(thing) {
thing.addEventListener('click', function() {
thing.classList.toggle('champagne');
thing.classList.toggle('braken');
});
});
"polyfill" - as long as the browser has
Array.prototype.forEach
NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach;
Array.prototype.forEach
的 Polyfill 是 here
关于javascript - 在纯 JavaScript 中交换一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42357659/