0

我有一些<article>带有类的标签,还有两个按钮根据它们的类显示和隐藏某些文章 - 但它不起作用

两个按钮.latestClick.mostViewedClick。每个都应该显示自己相应的<article>标签:<article>带有类的标签.latest应该在单击.latestClick按钮时显示,按钮也是如此.mostViewedClick。有些<article>标签有机器人类,所以当点击两个按钮中的任何一个时,它应该会显示出来。

jQuery

$('#featuredToggle ul li a').click(function (e) {
    e.preventDefault();

    if ($(this).hasClass('latestClick')) {
        $('article .mostViewed').toggleClass('hideArticle');
        $('article .latest').toggleClass('showArticle');
    } else if ($(this).hasClass('mostViewedClick')) {
        $('article .latest').toggleClass('hideArticle');
        $('article .mostViewed').toggleClass('showArticle');
    }
});

HTML:

<div id="featuredToggle">
    <ul>
        <li><a class="latestClick" href="#">Latest</a>
        </li>
        <li><a class="mostViewedClick" href="#">Most Viewed</a>
        </li>
    </ul>
</div>
<div class="box_mini block feed">
    <article class="latest"> <a href="post.html"><img src="img/175x175.jpg" alt="" /></a>

        <div class="content">
             <h4><a href="post.html">SUV's</a></h4>

        </div>
    </article>
    <article class="mostViewed hideArticle"> <a href="post.html"><img src="img/175x175.jpg" alt="" /></a>

        <div class="content">
             <h4><a href="post.html">Bakkies</a></h4>

        </div>
    </article>
    <article class="latest mostViewed"> <a href="post.html"><img src="img/175x175.jpg" alt="" /></a>

        <div class="content">
             <h4><a href="post.html">Hatch Back</a></h4>

        </div>
    </article>
    <article class="latest mostViewed"> <a href="post.html"><img src="img/175x175.jpg" alt="" /></a>

        <div class="content">
             <h4><a href="post.html">Sedan</a></h4>

        </div>
    </article>
    <article class="latest"> <a href="post.html"><img src="img/175x175.jpg" alt="" /></a>

        <div class="content">
             <h4><a href="post.html">Coupe</a></h4>

        </div>
    </article>
</div>

CSS:

.hideArticle {
    display: none;
}
.showArticle {
    display: block;
}

我在这里做错了什么?

4

2 回答 2

3
$('article .mostViewed').toggleClass('hideArticle');
$('article .latest').toggleClass('showArticle');

您的选择器中有一个不属于您的空间。

$('article.mostViewed').toggleClass('hideArticle');
$('article.latest').toggleClass('showArticle');
于 2013-03-19T21:18:19.887 回答
1

$('article .mostViewed')正在寻找一个带有子元素的文章标签,该子元素具有 class mostViewed。您需要删除空格以表明您正在寻找具有类的文章标签mostViewed

除此之外,使用切换可能会产生不良影响,特别是当有人不断点击同一个链接时。

您可以使用 jQuery show() / hide()大大简化您的代码,类似于:

$('#featuredToggle ul li a').click(function (e) {
    e.preventDefault();

    if ($(this).hasClass('latestClick')) {
        $('article.mostViewed').hide();
        $('article.latest').show();
    } else if ($(this).hasClass('mostViewedClick')) {
        $('article.latest').hide();
        $('article.mostViewed').show();
    }
});

这样,您也不会通过重复单击同一链接而获得不希望的结果。


演示- 使用show()hide()


于 2013-03-19T21:26:53.590 回答