gpt4 book ai didi

javascript - 单击时未切换类

转载 作者:行者123 更新时间:2023-12-02 14:29:41 24 4
gpt4 key购买 nike

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

当用户点击一个链接时,我想切换两个链接的类属性。

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

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

这是我当前的 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.targete.currentTarget (不确定这与事件委托(delegate)的配合效果如何)而不是

另请参阅Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?

关于javascript - 单击时未切换类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37947412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com