班级没有在点击时切换

时间:2016-06-21 14:37:31

标签: javascript jquery ecmascript-6

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

当用户点击链接时,我想切换两个链接的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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

Arrow functions没有自己的this,因此jQuery无法将其设置为当前元素。您必须使用“普通”功能作为事件处理程序,或者使用e.targete.currentTarget(不确定这与事件委派有何关系)而不是this

另见Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?

相关问题