简体   繁体   English

点击时未切换课程

[英]class not being toggled on click

I have a navigation control containing links. 我有一个包含链接的导航控件。

When a user clicks on a link, I want to toggle the class attribute of two links. 当用户单击链接时,我想切换两个链接的class属性。

I want to assign a class of 'targeted' to the clicked link. 我想为点击的链接分配“目标”类别。

I also want to remove the 'targeted' class from the prior selected link. 我也想从先前选择的链接中删除“目标”类。

here is my current es6 js. 这是我当前的es6 js。

 $(() => { //when one is clicked, remove the class from each of them and then add the class to the one that was clicked $(document).on("click", ".tools-cover .tools-container > .row > .col-xs-12 > nav ul li a", (e) => { $(document).find(".tools-cover .tools-container > .row > .col-xs-12 > nav ul li a").removeClass("targeted"); $(this).toggleClass("targeted"); }); //when the page has loaded, click the first nav link on the nav $(document).find(".tools-cover .tools-container > .row > .col-xs-12 > nav ul li:first-child a").click(); }); 
 <div class="tools-cover"> <div class="container tools-container"> <div class="row"> <div class="col-xs-12"> <nav> <ul> <li><a href="#">Feeds</a> </li> <li><a href="#">Wearisma links</a> </li> </ul> </nav> </div> </div> </div> </div> 

Arrow functions don't have their own this , so jQuery cannot set it to the current element. 箭头函数没有自己的this ,因此jQuery无法将其设置为当前元素。 You have to use a "normal" function as event handler, or use e.target or e.currentTarget (not sure how well this works with event delegation) instead of this . 您必须使用“正常”函数作为事件处理程序,或使用e.targete.currentTarget (不确定事件委派如何很好地工作)而不是this

See also Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? 另请参见Arrow函数与函数声明/表达式:它们是否等效/可互换?

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

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