我有一个包含链接的导航控件。
当用户点击一个链接时,我想切换两个链接的类属性。
我想为单击的链接分配“目标”类别。
我还想从之前选择的链接中删除“目标”类。
这是我当前的 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没有自己的 this
,因此 jQuery 无法将其设置为当前元素。您必须使用“普通”函数作为事件处理程序,或者使用 e.target
或 e.currentTarget
(不确定这与事件委托(delegate)的配合效果如何)而不是 此
。
另请参阅Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?
关于javascript - 单击时未切换类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37947412/