[英]Add/Remove all classes except event
Is there an easy way to remove all other classes except the eventarget in with JavaScript. 有没有一种简单的方法可以删除除JavaScript中的eventarget以外的所有其他类。
For example, if I have a UL: 例如,如果我有UL:
<ul>
<li>list element</li>
<li>list element</li>
<li>list element</li>
<li>list element</li>
<li>list element</li>
<li>list element</li>
</ul>
And I add click event listener with an event handler: 然后添加带有事件处理程序的click事件侦听器:
var UL = document.querySelector('ul');
function eventHandler(e) {
var thiz = e.target;
document.querySelectorAll('ul li').classList.remove("active");
thiz.classList.add("active");
}
UL.addEventListener('click', function (e) {
eventHandler(e);
});
How can I add a class on the element being clicked, while removing all the other "active" classes. 如何在要单击的元素上添加一个类,同时删除所有其他“活动”类。
Here's a fiddle http://jsfiddle.net/298ZV/ 这是一个小提琴http://jsfiddle.net/298ZV/
Without jQuery: 没有jQuery:
[].forEach.call(document.querySelectorAll('ul li'), function(a){
a.classList.remove('active');
});
This uses the Array.prototype.forEach()
to iterate over the NodeList and executes the function on each element. 这使用
Array.prototype.forEach()
遍历NodeList并在每个元素上执行函数。
You could also 'simplify' (though do note the scare-quotes...) a little further and do everything within the same forEach()
: 您还可以进一步“简化”(尽管要注意恐吓引号...),并在相同的
forEach()
完成所有操作 :
function eventHandler(e) {
var thiz = e.target;
[].forEach.call(document.querySelectorAll('ul li'), function(a){
a.classList[a == e.target ? 'add' : 'remove']('active');
});
}
With regards to concerns expressd by @adeneo, in comments to his answer , that should the li
elements contain other elements they will become the event.target
I've added a simple closest()
function to find the element you're looking for: 关于@adeneo表示的关注,在对他的回答的评论中 ,如果
li
元素包含其他元素,它们将成为event.target
我添加了一个简单的 closest()
函数来查找您要查找的元素:
var UL = document.querySelector('ul');
function closest(origin, elem) {
var current = origin;
elem = elem.toLowerCase();
while (current.tagName.toLowerCase() !== 'body' && current.tagName.toLowerCase() !== elem) {
current = current.parentNode;
}
return current;
}
function eventHandler(e) {
var that = closest(e.target, 'li');
[].forEach.call(document.querySelectorAll('ul li'), function(a) {
a.classList[that === a ? 'add' : 'remove']('active');
});
}
UL.addEventListener('click', function (e) {
eventHandler(e);
});
References: 参考文献:
Do it a little differently, attach the event handler to the LI's, and keep them in a variable, then iterate over the LI's and remove the class from the ones that aren't this
做到这一点有点不同,附加的事件处理程序LI的,并保存在一个变量,然后遍历LI的和不属于那些删除类
this
var LI = document.querySelectorAll('ul li');
for (var i=LI.length; i--;) {
LI[i].addEventListener('click', eventHandler);
}
function eventHandler() {
this.className = 'active';
for (var i=LI.length; i--;) {
if (LI[i] != this) LI[i].className = '';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.