[英]javascript - removeClass to elements that has it
I am looking for a pure javascript replacement for this jquery code: 我正在寻找这个jquery代码的纯javascript替换:
$().evt(function(){
$('.class').removeClass('active');
$(this).addClass('active');
})
this is how i am trying 这就是我的尝试方式
node.addEventListener('contextmenu', function(e){
e.preventDefault();
var currentActive = document.querySelectorAll('.active');
alert(currentActive.length);
currentActive.className = '';
this.className = 'active';
});
fiddle: http://jsfiddle.net/toniweb/Wx8Jf/34/ 小提琴: http : //jsfiddle.net/toniweb/Wx8Jf/34/
But current active class is not removed 但是当前的活动类不会被删除
You will need to access the correct node as document.querySelectorAll
returns a NodeList
您将需要以
document.querySelectorAll
访问正确的节点返回NodeList
Try this, 尝试这个,
node.addEventListener('contextmenu', function(e){
e.preventDefault();
var currentActive = document.querySelectorAll('.active');
if(currentActive[0]) { // first item with class 'active'
currentActive[0].className = '';
}
this.className = 'active';
});
Updated fiddle: http://jsfiddle.net/Wx8Jf/35/ 更新小提琴: http : //jsfiddle.net/Wx8Jf/35/
Try this: 尝试这个:
node.addEventListener('contextmenu', function(e){
e.preventDefault();
var currentActive = document.querySelectorAll('.active');
for (var i = 0; i < currentActive.length; i++) {
currentActive[i].classList.remove('active');
}
this.className += ' active';
});
This will remove only the active
class from those nodes. 这将仅从这些节点中删除
active
类。
Try this to remove any class from the list of the specific element: 试试这个从特定元素列表中删除任何类:
var removeClassName = 'active';
var classes = element.className.match(/\S+/g);
var ind = classes.indexOf(removeClassName);
if (ind >= 0)
classes.splice(index, 1);
element.className = classes.join(' ');
Try this: 尝试这个:
var node = mainNodes[i];
node.addEventListener('contextmenu', function(e){
e.preventDefault();
var currentActive = document.querySelectorAll('.active');
for (element in currentActive) {
element.className = element.className.replace(' active', '');
}
e.target.className += ' active';
In the context of the event handler, this will link to the anonymous function. 在事件处理程序的上下文中,这将链接到匿名函数。 Use e.target instead.
请改用e.target。
This code will remove the .active class on all elements that have it and add this class to the event target. 此代码将删除包含它的所有元素上的.active类,并将此类添加到事件目标。 Other answers only work on the first element with this class, is it what you want?
其他答案仅适用于此类的第一个元素,它是您想要的吗?
Updated fiddle: http://jsfiddle.net/Wx8Jf/36/ 更新小提琴: http : //jsfiddle.net/Wx8Jf/36/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.