2013-02-21 18 views
0

我正在觸發一個基於在URL中傳遞的哈希的JavaScript。是我的網址哈希定義爲jquery數據嗎?

但是,如果哈希不是我期望的那樣,我不想觸發。

預期散列列表使用data-category屬性定義。

我怎樣才能得到這個數據的數組,所以我可以看到我的散列是否在數組中?

這裏是我給出的HTML:

<div class="filter_padder" id="nav_channels"> 
     <div class="filter_wrapper" style="max-width:650px;"> 
      <div class="filter selected" data-category="cat-all">ALL</div> 
      <div class="filter" data-category="MusicWorld">MusicWorld</div> 
      <div class="filter" data-category="Awards">Awards</div> 
      <div class="filter" data-category="MX">Exchange</div> 
      <div class="filter last-child" data-category="Com">Community</div> 
      <div class="clear"></div> 
     </div> 
    </div> 

的Javascript:

// set any hash in the url to a variable 
var hash = location.hash.replace('#', ''); 

// see if my hash is expected (would like to handle this dynamically) 
if(hash === (cat_all|Awards|MX|Com)) { 
    doSomething(); 
} 

但我不知道如何動態地構建元素列表來比較「散」。我認爲這是沿線的:

$('#nav_channels').data('category'); 

但不能得到那個工作。

回答

1

試試這個:

var hash = location.hash.replace('#', ''); 
if($('.filter[data-category="'+hash+'"]').length) { 
    doSomething(); 
}; 
0

你可以得到的值到一個數組,像這樣:

var cats = $('[data-category]').map(function() { 
    return $(this).data('category'); 
}).get();