单击链接时会启动此功能。它需要删除所有' .is-active'具有属性[data-route]的元素上的类。并添加课程' .is-active'在与我点击的链接相关联的[data-route]元素上。
toggle: function(section){
var sections = document.querySelectorAll('[data-route]');
for (i = 0; i < sections.length; i++){
document.querySelector('[data-route]').classList.remove('is-active');
}
document.querySelector(section).classList.add('is-active');
}
但这不起作用。它没有删除类?
参见示例:http://jordypouw.github.io/myFED2/deeltoets1/index.html
P.S。它必须采用vanilla JavaScript。
答案 0 :(得分:2)
toggle: function(section){
var sections = document.querySelectorAll('[data-route]');
for (i = 0; i < sections.length; i++){
sections[i].classList.remove('is-active');
// querySelectorAll return an array of dom elements, u can access them directly.
}
// I suppose in your case that ' section ' variable is the clicked element so :
section.classList.add('is-active')
// if not you have to store the dom element from the event, and add the class here.
}
答案 1 :(得分:0)
你可以这样做:
for (var item of document.querySelectorAll('[data-route]')) {
item.classList.remove('is-active');
}
这是 ecmascript6 ,因此它无法在旧浏览器上运行。我喜欢它,因为它干净而且漂亮。要让它在其他浏览器上工作,您必须convert将节点集合转换为真实数组,这样您就可以循环它。
答案 2 :(得分:0)
为点击的项目设置变量..
jQuery('.clicker-item').on("click", function(){
var clicked = jQuery('.clicker-item').not(jQuery(this));
clicked.removeClass("active")
jQuery(this).toggleClass("active")
});
答案 3 :(得分:0)
toggle: function(section){
document.querySelectorAll("[data-route]").forEach( e => {
e.classList.remove("is-active");
});
// querySelectorAll return an array of dom elements, u can access them directly.
// I suppose in your case that ' section ' variable is the clicked element so :
document.querySelectorAll("[data-route]").forEach( e => {
e.classList.add("is-active");
});
// if not you have to store the dom element from the event, and add the class here.
}
答案 4 :(得分:0)
我觉得其他答案不够简洁。
toggle: (s) => {
// Find all other sections and remove the active class:
document.body.querySelectorAll('[data-route]').forEach(i => i.classList.remove('is-active'))
// Add active to the inputted section:
s.classList.add('is-active')
}
答案 5 :(得分:-2)
不应该是这样的:
toggle: function(section){
var sections = document.querySelectorAll('[data-route]');
for (i = 0; i < sections.length; i++){
document.querySelector('[data-route]').removeClass('is-active');
}
document.querySelector(section).addClass('is-active');
}
编辑:对不起,我应该说removeClass和addClass