jQuery的.not()的香草javascript等效项是什么? [英] Which is the vanilla javascript equivalent for .not() of jQuery?

查看:89
本文介绍了jQuery的.not()的香草javascript等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将类添加到列表的循环.我希望将此类添加到除单击元素之外的所有其他元素上.我在互联网上找到了以下内容:

I'm trying to create a loop which adds a class to a list. I wish this class to be added on all the elements except the element which is being clicked. I found the following on the internet:

$('.elements').click(function(){
     $('.elements').not(this).each(function(){
         // do something
     });
})

有与香草javascript等效的东西吗?我找不到来自 .not()的转换.

Is there an equivalent to vanilla javascript? I cannot find the conversion from .not().

推荐答案

您发布的完整代码的原始版本将是这样.相当详细的TBH,而无需帮助程序向每个el添加点击侦听器.

The vanilla version of the full code you posted would be something like this. Quite verbose TBH without having the helper to add a click listener to each el.

var els = document.querySelectorAll('.elements');
[].forEach.call(els, function(el, i, els) {
    el.addEventListener('click', function() {
        [].forEach.call(els, function(el) {
            if(el !== this) {
                // do something
            }
        }, this);
    });
});

这篇关于jQuery的.not()的香草javascript等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆