使用jQuery跟踪/激活点击的文章

Keep the clicked article tracked / active using jQuery

本文关键字:文章 激活 jQuery 跟踪 使用      更新时间:2023-09-26

我面临着jQuery父ulli打开的一个问题,下面是我的html结构:

<div>
  <ul>
     <li class="has-sub">
        <a href="#">1</a>
        <ul>
           <li><a href="#">1.1</a></li>
           <li><a href="#">1.2</a></li>
           <li class="has-sub">
             <a href="#">2</a>
             <ul>
                <li><a href="#">2.1</a></li>
                <li><a href="#">2.2</a></li>
                <li class="has-sub">
                  <a href="#">3</a>
                  <ul>
                      <li><a href="#">3.1</a></li>
                      <li><a href="#">3.2</a></li>
                      More...
                  </ul>
                </li>
             </ul>
           </li>
        </ul>
     </li>
  </ul>
</div>

j查询:

$(function () {
  $('a').each(function () {
    if ($(this).prop('href') == window.location.href) {
        $(this).addClass('activation');
    }
  });
});

.css:

.open > a:after,
.open > a:before {
 -webkit-transform: rotate(45deg);
 -moz-transform: rotate(45deg);
 -ms-transform: rotate(45deg);
 -o-transform: rotate(45deg);
 transform: rotate(89deg);}

activation类添加,但不打开父级 ul li。

我需要哪个类是激活然后这个父 ul li 打开那个时间。

如何获得此解决方案?

似乎这就是你想问的:

$(function() {
  $('a').click(function() {
    if ($(this).prop('href') == window.location.href) {
      $('li').removeClass('open');
      $('a').removeClass('activation');
      $(this).addClass('activation').closest("li").addClass("open");
    }
  });
});

这是JSFiddle演示

请通过检查元素检查结构。

你需要使用以下js:

$(function() {
  $('a').removeClass('activation');
  $('ul').removeClass('open');
  $('a').each(function() {
    if ($(this).attr('href') == '#') { //replace your url
      $(this).addClass('activation');
      $(this).parent().parent().addClass('open');
    }
  });
});

查找工作演示

这是我

最后的jQuery代码:

$(function () {
  $('a').each(function () {
    if ($(this).prop('href') == window.location.href) {
        $(this).addClass('activation');
        $(this).parent().closest('.has-sub').addClass('open active');
    }
  });
});

但是现在只工作第二位,不工作第三或第四位

.css:

.active {
  display: block;
}