2017-03-01 24 views
1

所以我有一個頁面有3個按鈕來過濾頁面上的內容。使用網址哈希執行點擊事件

<section class="solution-filter"> 
    <div class="wrapper"> 
     <button class="fact-sheet" data-target_category="fact-sheet" disabled="">Fact sheet</button> 
     <button class="demo" data-target_category="demo">Demo</button> 
     <button class="apps" data-target_category="apps">Apps and connectors</button> 
    </div><!-- /.wrapper --> 
</section> 

我希望能夠執行一個按鈕點擊取決於URL散列。

例如http://example.com/#demo 將在<button class="demo" data-target_category="demo">Demo</button>

if (window.location.hash) { 
    $(document).click($('<button>').data('target_category', (window.location.hash)); 
} 
+0

看起來你已經做到了。有什麼問題 ? –

+0

你可能只是想聽'hashchange'事件? – adeneo

回答

1

你有正確的想法進行點擊,但語法你使用,以提高點擊事件是不完全正確。您需要先使用hash值來選擇該元素,然後在其上調用click()trigger('click')

if (window.location.hash) { 
    $('.' + window.location.hash.substr(1)).click(); 
} 

注意,substr()調用用於從字符串的開始刪除#

上述代碼將在頁面加載時適用於您。如果你也想知道,當頁面加載後的哈希值發生變化,你可以使用hashchange事件window的:

$(window).on('hashchange', function() { 
    if (window.location.hash) { 
    $('.' + window.location.hash.substr(1)).click(); 
    } 
}); 
+0

我建議添加一個檢查是否匹配哈希內容的元素是否真的被發現 - 這樣的東西往往會拋出討厭的錯誤,否則。 – CBroe

+1

@CBroe即使沒有發現任何東西,jQuery仍然會從選擇器中返回一個對象。如果沒有找到元素,您可以確保上述代碼不會產生錯誤。如果URL中的哈希值不是一個有效的選擇器 –

+1

是的,我可能把它與更復雜的情況混淆了(比如你想要初始化一個jQuery插件,$(' .doesnotexist')。someSlider(...)',當沒有匹配元素時通常會導致錯誤。)關於無效選擇器的好處(可能使用正則表達式來檢查它,但另一方面,可能並不真正是必要的,只要你與怪異的哈希鏈接無關。) – CBroe

1

你需要得到button然後觸發click()$('<button>')將創建一個jQuery對象不是目標所需元素。

if (window.location.hash) 
    $('button[data-target_category="'+window.location.hash.substr(1)+'"]').click();