Open particular Jquery accordion pan based on current page URL

痞子三分冷 提交于 2019-12-07 19:05:59

问题


I have a Jquery accordion, accordion has pan's, list elements and anchor tags in list elements, href attributes of anchor tags have current page URL's. I just want that when a page is visited a particular panel (which contains that anchor tag) automatically opens and its list element should become active. I have code which make accordion and snippet in end which make list element active. But list element is not active and panel is not opened. I think I am missing something badly. Here is code:

<script>
  $.ajax({
    url: "/categories",
    type: 'GET',
    success: function(data) {
      var content = "";

      content += '<div id="category-navigation">';
      for (i = 0; i < data.length; i++) {

        content += '<div class="head">';
        content += '<label class="categoryLables">' + data[i].title;
        content += '</label>';

        content += '<div>';
        content += '<div class="boardsMargin">';
        content += '<ul>';

        for (j = 0; j < data[i].assigned_boards.length; j++) {

          content += '<li>';
          content += "<a href='/#categories/" + data[i].id + "/boards/" + data[i].assigned_boards[j].id + "'>";
          content += data[i].assigned_boards[j].name;
          content += '</a>';
          content += '</li>';
        }

        content += '</ul>';
        content += '</div>';
        content += '</div>';
        content += '</div>';
      }
      content += '</div>';

      $("#myNavigation").html("");
      $("#myNavigation").html(content);

      $('.head').accordion({
        heightStyle: "content",
        active: true,
        collapsible: true
      });

      $('.head li').each(function() {
        li = $(this);
        a = $('a', li);

        myUrl = "";

        myUrl += (location.protocol + "//" + location.hostname +
          (location.port && ":" + location.port));
        myUrl += (a.attr('href'));


        if (myUrl == window.location.href) {
          console.log(myUrl);
          console.log(window.location.href);
          li.addClass('active');

        }
      });

    }

  });

</script>

Brief Demo

My question is quite similar to this question. And I am following its 1st answer.

For more clear view, this is picture of my accordion.

As a side note: I am working in ruby 2.2.1 and rails 4.1


回答1:


This code should do the trick:

$(document).find("a[href*='" + '/' + window.location.pathname + "']").parents(".head").find("h3").trigger("click");

Example of where to place your code



来源:https://stackoverflow.com/questions/31971860/open-particular-jquery-accordion-pan-based-on-current-page-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!