Ссылки хеш-якоря не могут найти / target ID целевой элемент DOM (при определенных обстоятельствах) - PullRequest
0 голосов
/ 10 октября 2019

Хэш-ссылочные ссылки не могут найти / target ID целевой элемент DOM (и, следовательно, не могут вызвать изменение вкладки JS UI)

Привет, посетите https://eurosurveillance.org/content/10.2807/1560-7917.ES.2019.24.40.1900157 и прокрутите вниз полный текст HTML (показанный в этомвкладку) и попробуйте щелкнуть ссылку «Дополнение 1» или «Дополнение 2», обратите внимание, что ничего не происходит.

Нет ничего умного в ссылках, они являются обычными html хэш-ссылками ....

<a href="/content/10.2807/1560-7917.ES.2019.24.40.1900157#supplementary_data">Supplement 1</a>

Теперь, если вы заходите на ту же страницу, но на этот раз выполните перезагрузку со следующим URLв адресной строке браузера https://eurosurveillance.org/content/10.2807/1560-7917.ES.2019.24.40.1900157#html_fulltext (обратите внимание, что единственным изменением является хэш в URL). Теперь попробуйте следовать тем же инструкциям, что и раньше, и вы заметите, что по какой-то причине теперь идет ссылка привязки и срабатывает вкладка привязки JS, это поведение, которое я ожидаю

Пожалуйста, сообщите. заранее спасибо.

1 Ответ

0 голосов
/ 11 октября 2019

Большое спасибо, проблема была решена путем рефакторинга кода respive-tabs.js:

$(document).ready(function() {
        //responsive tabs API code.
    var Tabs = {

          init: function() {
            this.bindUIfunctions();
            this.pageLoadCorrectTab();
          },

          bindUIfunctions: function() {

            // Delegation
            $(document)
              .on("click", ".js-transformer-tabs a[href^='#']:not('.active, .disabled')", function(event) {
                Tabs.changeTab(this.hash);
                event.preventDefault();
              })
              .on("click", ".js-transformer-tabs a.active, .js-transformer-tabs a.disabled", function(event) {
                Tabs.toggleMobileMenu(event, this);
                event.preventDefault();
              })
             .on("click", ".js-textoptionsFulltext a.html:not('.disabled')", function(event) {      
                    //console.log("tab?" + this.hash);
                    event.preventBubble=true;
                     var anchorTab = Tabs.changeTab(this.hash);
                     anchorTab.trigger("click"); //trigger click event in this case it will be html fulltext.
                    //event.preventDefault();        
                });
             //We also need to handle the back state by telling the browser to trigger the tab behaviour!   
            $(window).on('popstate', function(e) {
               anchor = $('[href="' + document.location.hash + '"]');
               if (anchor.length >  0) {
                   Tabs.displayTab(anchor);
               } else {
                  var defaultAnchor =  $('.js-transformer-tabs li.active a');
                  if (defaultAnchor) {
                      Tabs.displayTab(defaultAnchor)
                  }
               }
            });
            
          },

          changeTab: function(hash) {
             
            var anchor = $(".js-transformer-tabs a[href='" + hash + "']");
            var activeTab = anchor.find('span strong');
            Tabs.displayTab(anchor);

            $(".js-dropdown li").hide();
             
            $(".js-mobile-tab").text($(activeTab).text());
                
            // update history stack adding additional history entries.
            // pushState is supported!
            history.pushState(null, null,  hash);

            // Close menu, in case mobile
            return anchor; // make property available outside the function

          },
          pageLoadCorrectTab: function() {
              //console.log("document.location.hash: " + document.location.hash);
            if   (document.location.hash.length > 0) {
                // If the page has a hash on load, go to that tab
                 var anchor = $(".js-transformer-tabs a[href='" + document.location.hash + "']");
                 if (!anchor.hasClass("disabled")) {
                     var anchorTab = this.changeTab(document.location.hash);
                     // this is a further amendment to allow the fulltext and 
                     //(any future event if its attached) to load when bookmarking a page with a particular tab. 
                     anchorTab.trigger("click");
                 }
              } else if ($(".js-transformer-tabs .active.tabIcon .active").length > 0) {
                  // go to which ever tab is defined as active in the JSP page and trigger a click on it 
                  // but, only when no hash in the url
                  var activeTab = $(".js-transformer-tabs .active.tabIcon .active");  
                      activeTab.trigger("click"); //trigger click
              }
          },

          toggleMobileMenu: function(event, el) {
            $(el).closest("ul").toggleClass("open");
          },
          displayTab: function(anchortab) {
                var url = anchortab.attr("href");
                //console.log("url" + url);
                var divtabContent = $(url);
                
                // activate correct anchor (visually)
                anchortab.addClass("active").parent().siblings().find("a").removeClass("active");

                // activate correct div (visually)
                divtabContent.addClass("active").siblings().removeClass("active");
            }

    }


    Modernizr.load([{
    //test
    test : Modernizr.history,
        //if yes then do nothing as nothing extra needs loading....
        
        //if no then we need to load the history API via AJAX
    nope : ['/js/' + ingentaCMSApp.instanceprefix + '/vendor/history.min.js'],
        
    complete : function() {
        
        var location = window.history.location || window.location; 
            Tabs.init();
    }

    }])
    

  });

    //end of responsive tabs API code.
    



    $(".js-select").click(function(){
        $(".js-dropdown li").slideToggle();
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...