首页 > 解决方案 > Onclick 不是这个

问题描述

我为侧边栏创建了一个功能,当单击它时,它会向下滑动第一个 href,然后任何不是它的东西都会向上滑动。这工作正常,直到我需要使用“onclick”调用该函数,这意味着 $(this) 不能正常工作,因为它只能调用 (this) 。我正在使用标签生成器,因此只能调用一个唯一的事件侦听器。

JS

$(".foo > a").each(function () {
    $(this).click(function () {
        $(this).siblings(".sibling").slideToggle();
        $(this).toggleClass("active");

        $(".foo > a").not(this).siblings(".sibling").slideUp();
        $(".foo > a").not(this).removeClass("active");

    });
});

C#

a.MergeAttribute("onclick", "Click.call(this)");

不是这个以侧边栏为目标,也不是向上滑动

标签: c#jqueryhtml

解决方案


要不将 CSS 类添加到当前目标,只需删除当前 CSS 并添加到其兄弟姐妹。

$(".foo > a").click(function () {
  $(this)
    .removeClass('active')
    .siblings()
    .addClass('active');
});
.foo {
  display: flex;
}

.foo a {
  border: 1px solid black;
  color: black;
  padding: 15px;
  margin: 15px;
  text-decoration: none;
}

.foo a.active {
  background: black;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">
  <a href="#">Link1</a>
  <a href="#">Link2</a>
  <a href="#">Link3</a>
</div>


推荐阅读