2017-08-08 40 views
1

我工作的活動頁面上,使用一組過濾器來查詢職位WordPress站點項目;對於過濾器的標記如下:jQuery的:添加類過濾含有活性項,佔分頁

<div class="event-filter"> 
    <a href="/events">All Events</a> 
    <a href="/events?event-type=conference">Conferences</a> 
    <a href="/events?event-type=webinar">Webinars</a> 
    <a href="/events?event-type=learning">Learning</a> 
    <a href="/past-events/">Past Events</a> 
</div> 

我使用jQuery添加一個active類目前取其過濾器在使用中,其簡單的代碼如下:

$('.event-filter a').each(function() { 
    if (this.href == window.location.href) { 
     $(this).addClass("active"); 
    } 
}); 

這個工程除了在所得到的職位是拼版的情況下完全正常的,作爲URL的變化,以反映當前頁面,即/events/page/2/?event-type=conference。如何修改我的JS給active類添加到當前的過濾器,如果URL 包含各自event-type期限,但也說明了「所有事件」,因此追加類爲「所有事件」的時候,其他過濾器不正在使用?有幾點需要注意:「過去事件」選項僅鏈接到歸檔頁面,該頁面是主要的可過濾「事件」頁面的單獨模板;此外,這些過濾器不使用Ajax,它們只是通過URL參數改變WordPress查詢。感謝您的任何見解!

回答

1

通過它的外觀,你將不得不做兩部分的檢查,我會嘗試這樣的:

$('.event-filter a').each(function() { 
    var currentHref = window.location.href.split('?'); // ['https://myexamplesite.com/events/page/2', 'event-type=conference'] 
    var thisHref = this.href.split('?'); // ['https://myexamplesite.com/events', 'event-type=conference'] 
    var currentHrefHasQuery = currentHref.length > 1 ? true : false; // true 
    var thisHrefHasQuery = thisHref.length > 1 ? true : false; //true 

    if (currentHrefHasQuery != thisHrefHasQuery) { 
     return; // they don't match 
    } 

    if (currentHrefHasQuery && currentHref[1] == thisHref[1]) { // if they have a query and the query is the same, it's a match! 
     $(this).addClass("active"); 
    } else if (!currentHrefHasQuery && currentHref[0].indexOf(thisHref[0]) > -1) { //check to see if the current href contains this' href 
     $(this).addClass("active"); 
    } 
}); 

這絕對可以簡化,但希望這是相當容易閱讀。

小提琴:https://jsfiddle.net/m0hf3sfL/

+0

感謝你的津協助,而「所有事件」被激活預期,個別過濾器點擊時,所有這三個與定義越來越與此同時類的事件類型;你知道這裏會發生什麼嗎? – nickpish

+0

我的不好,修好了!這是'else if'語句的問題。 –

+0

太棒了,非常感謝!現在所有人都在工作。爲了教育的目的,'currentHrefHasQuery'和'thisHrefHasQuery'在檢查'length'時究竟發生了什麼?再次感謝。 – nickpish