繁体   English   中英

点击时未切换课程

[英]class not being toggled on click

我有一个包含链接的导航控件。

当用户单击链接时,我想切换两个链接的class属性。

我想为点击的链接分配“目标”类别。

我也想从先前选择的链接中删除“目标”类。

这是我当前的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> 

箭头函数没有自己的this ,因此jQuery无法将其设置为当前元素。 您必须使用“正常”函数作为事件处理程序,或使用e.targete.currentTarget (不确定事件委派如何很好地工作)而不是this

另请参见Arrow函数与函数声明/表达式:它们是否等效/可互换?

暂无
暂无

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

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