Ориентация <a> на <h> родительского элемента с помощью jQuery

По какой-то причине у вас чертовски тяжелые времена с этим... необходимая разметка:

<a href="about.htm#test">About PFD</a>
<ul id="acc1" class="accordion hidden" style="list-style-type:none">
  <li>
    <h2 id="test" class="header">Our Story</h2>

    <div class="inner">
      <ul style="list-style-type:none">
        <li>
          <h3 class="header">Stand Alone: PFD is a different kind of company.</h3>
          <div class="inner">
              <p align="justify" class="bodytext">One that doesn’t conform and isn’t constrained by what others have done or are currently doing as none of that will affect what we will do. At every position, at every task and under any and all circumstances we intend to leave no doubt. Whether in the quality of our products, craftsmanship, client service, form of process, source relationships or our environmental footprint we widen the gap between role players and innovators. What makes it fundamentally easy to do just that at PFD is that one can always count on the individual next to them doing the exact same thing. </p>
          </div>
        </li>
        <li>
          <h3 class="header">Ambassadors:</h3>
          <div class="inner">
              <p align="justify">As much as a finished product ties into its original raw material so does the heart of a company tie into its people. A company is the embodiment of the collective personas that give it purpose, perform its tasks and plan its future. The quest for excellence as a notion or a process is flawed as anyone truly in the pursuit of excellence knows they will never find it. They will arrive at the point they dreamed of to realize they have already dreamed of something more excellent. Any viable business must look to secure today while eyeing its next foothold by which it will push itself even higher. Ascension as a phenomenon is only made possible by the feats of real people with extraordinary abilities and even more passion. PFD has embarked upon the perpetual journey negotiated by its ambassadors, broad and far reaching when it can be, narrow and precise when it has to be, but always with the understanding that it will never get to the end as there will never be one.</p>
          </div>
        </li>
        <li>
          <h3 class="header">Tradition:</h3>
          <div class="inner">
              <p align="justify">Present day PFD is a privately held company, owned and operated by family for family. Our business is conducted for the service of our clients and for the families of all the individuals who place their collective talents within our walls and whose deeds spread far beyond that. We encourage pride and passion at every level as nothing great has ever been built or maintained without those components. PFD is a premier processor of high end meat products with a strong focus in USDA Prime Beef. Boasting an extensive selection of products and services ranging from primal cuts to specialized preparation of goods, we at PFD stand ready to achieve and surpass all expectations. From our mail order fulfillment, to portion cut steaks, to sub-primal cuts, we continue to meet the ever changing needs of our clients. The key to our success remains our willingness and ability to provide what our customers need.

                <br>
                <br>
            PFD and subsidiary companies have been synonymous with wholesale meat and in particular Carcass beef packing for many decades. Our tradition of producing quality products and expertise in custom fabricating has been one of distinction and dependability. Today that tradition and expertise have morphed into an establishment which is a leading and cutting edge fabricator of USDA Prime and Higher Beef, Portion Control Specialists, Dry Aging, Custom Grinds, Specialty and Value Added goods and services. Setting the standard for meat operations to follow in respect to quality control and public safety coupled with a legacy of decades in the business, PFD is forging the path of a distinct and well organized institution in the meat industry. The PFD name has been and continues to be recognized as a top tier purveyor and innovator in all that is meat.</p>
          </div>
        </li>
      </ul>
    </div>
  </li>
 </ul>

JQuery это (важная часть здесь):

<script type="text/javascript">

 if(window.location.hash) {
      var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
      $('#' + hash + ' .header .h + a .trigger').addClass('open');
      // hash found 
  } else {
      // No hash found
  }
</script>

Моя проблема заключается в попытке выбрать тег, который находится внутри родительского элемента или тегов в разобранном html, который включает в себя классы, основанные на плагине accordion js, который я использую, по сути, я хочу добавить "открытый" класс в аккордеон элементы, которые я хочу открыть при загрузке страницы. URL здесь:

http://primefooddistributor.com/about.htm

1 ответ

Когда вы проверяете сайт, это не <h3> там, кроме <h2> элемент, аккордеонный плагин мог бы заменить этот. Так что селектор должен быть: $('#' + hash + ' h2.header.h > a.trigger') или просто отрезать этот элемент заголовка $('#' + hash + ' .header.h > a.trigger'),


Если <a> также создается с помощью плагина аккордеона, что, вероятно, является другой проблемой. Вы должны проверить с плагином, чтобы увидеть, но большинство плагинов не имеет обратного вызова, чтобы сообщить вам, что он завершил применение.

Хорошее решение - проверить рекурсивно, используя setInterval и просто очистить его потом.

if (window.location.hash) {
    var hash = window.location.hash.substring(1); 

    var interval = setInterval(function () {
        var a = $('#' + hash + ' .header.h > a.trigger');
        if(a.length){
            //<a> is found this time! apply stuff here
            a.addClass('open');
            /*go to <div class="outer"> and apply display block:
             traverse to the parent 'li' using closest() and find the <div>
             then apply css('display','block') or simply show() 
              since div has a default display block*/
            a.closest('li').find('.outer').css('display','block');


            clearInterval(interval);
        }                       
    }, 500);
} else {
    // No hash found
}

если вам нужно добавить событие в <a> Вы можете подать заявку, используя .on()

Другие вопросы по тегам