3

我正在开发一个 WordPress 主题,并使用 JS 来根据切换的类别项目实时过滤帖子结果。类别链接是刚刚创建的wp_list_categories();,帖子列表是用WP_Query();

目前我在 JS 中设置了唯一的帖子 ID 来完成这项工作,但要让其他人使用主题,我不希望他们每次添加新类别时都必须编辑 JS。基本上,无论添加多少类别,我都希望拥有 JS 功能和过滤帖子。

我当前的标记是这样的:

<section id="sidebar">
    <ul>
        <li class="cat-item cat-item-1"></li>
        <li class="cat-item cat-item-2"></li>
        <li class="cat-item cat-item-3"></li>
    </ul>
</section>

<section id="postlist">
    <div class="1post apost"></div>
    <div class="2post apost"></div>
    <div class="3post apost"></div>
</section>

我的JS如下:

$(".cat-item-1").click( function() {
    $('.1post').toggle('slow');
});

$(".cat-item-2").click( function() {
    $('.2post').toggle('slow');
});

$(".cat-item-3").click( function() {
    $('.3post').toggle('slow');
});

当我每次为每个类别和帖子 ID 明确键入它时,这工作正常,但我试图完成类似的事情:

$(".cat-item-" + (dynamic cat ID)).click( function() {
    $("." + (dynamic post ID that matches cat ID) + "post").toggle('slow');
});

这是可能吗?当谈到 JS 时,我不是世界上最有经验的人,所以如果解决方案让我眼前一亮,我深表歉意!我在这里添加了这个作为小提琴:http: //jsfiddle.net/davemcnally/5QZcw/ - 提前致谢!

4

1 回答 1

3

看看我的解决方案:http: //jsfiddle.net/EP96x/

$('.cat-item').click(function () {
    $('.apost').eq($(this).index()).toggle();
});

它计算cat-item您单击的具有类的元素(第一个、第二个等...),然后使用该类切换相应的元素apost

编辑:正如评论中指出的那样,元素出现故障存在一定的风险。如果是这种情况,则需要使用正则表达式以将链接与正确的元素匹配:

http://jsfiddle.net/HKkq5/

$('.cat-item').click(function () {
    var num = $(this).attr('class').match(/cat-item-(\d+)/)[1];
    $('.' + num + 'post').toggle();
});
于 2012-09-29T14:53:42.650 回答