简体   繁体   English

Vanilla Javascript - 向元素1添加类,并在单击元素1时从元素2中删除类

[英]Vanilla Javascript - Adding class to element 1 and remove class from element 2 on click of element 1

I've been told I can no longer use jQuery on a project I'm building, so I'm forced to use vanilla Javascript which can sometimes be way over my head. 有人告诉我,我不能再在我正在构建的项目中使用jQuery,所以我不得不使用vanilla Javascript,这有时可能会超出我的想象。 I'm hoping to simply convert this jQuery to js. 我希望简单地将这个jQuery转换为js。 I've searched and searched on Stack Overflow to no avail, but I feel like it shouldn't be that difficult. 我在Stack Overflow上搜索和搜索无济于事,但我觉得它应该不那么困难。 Any help would be amazing! 任何帮助都会很棒!

$('.navbuttoncontainer a').on( 'click', function() {
$('.navbuttoncontainer .current').removeClass('current');
$(this).addClass('current');

You could attach a click event listener to the .navbuttoncontainer element. 您可以将click事件侦听器附加到.navbuttoncontainer元素。

Then determine whether the a element was clicked by checking the tag name of the target element ( e.target ). 然后通过检查目标元素的标记名称( e.target )来确定是否单击了a元素。 Use the .add() / .remove() methods on the classList property of the element in order to add/remove the class. 使用.add() / .remove()的方法classList属性的元素,以添加/删除类。

 document.querySelector('.navbuttoncontainer').addEventListener('click', function (e) { var target = e.target; if (target.tagName === 'A') { e.currentTarget.querySelector('.current').classList.remove('current'); target.classList.add('current'); } }); 
 .current { color: #f00; } 
 <div class="navbuttoncontainer"> <a class="current">Initially current item</a> <a>Second item</a> <a>Third item</a> </div> 

All modern browsers have support for document.querySelector / document.querySelectorAll , which are essentially the same thing as the jQuery $ function. 所有现代浏览器都支持document.querySelector / document.querySelectorAll ,它们与jQuery $函数基本相同。

(For supported browser info check out http://caniuse.com/#feat=queryselector . (有关支持的浏览器信息,请查看http://caniuse.com/#feat=queryselector

Instead of calling addClass / removeClass on a jQuery object, the DOM API exposes a property of elements called className . DOM API不是在jQuery对象上调用addClass / removeClass ,而是公开名为className的元素的属性。 This is same as the class attribute on an element: 这与元素上的class属性相同:

this.className = 'current'; this.className ='current';

Lastly, event handlers are registered with the addEventListener function. 最后,使用addEventListener函数注册事件处理程序。 The arguments are the event name and the event handler function. 参数是事件名称和事件处理函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM