I have a navigation control containing links.
When a user clicks on a link, I want to toggle the class attribute of two links.
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.
$(() => { //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. 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
.
See also Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.