0

我正在触发基于 url 中传递的哈希的 javascript。

但是,如果哈希不是我期望的,我不想触发。

预期的哈希列表是使用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');

但不能让它发挥作用。

4

2 回答 2

1

试试这个 :

var hash = location.hash.replace('#', '');
if( $('.filter[data-category="'+hash+'"]').length ) { 
  doSomething();
};
于 2013-02-21T15:41:22.603 回答
0

您可以像这样将值放入数组中:

var cats = $('[data-category]').map(function() {
    return $(this).data('category');
}).get();
于 2013-02-21T15:43:17.317 回答