如何在点击时显示div?

时间:2017-01-24 01:55:33

标签: javascript jquery html ruby-on-rails

这应该相当简单,但我对Javascript并不熟悉,所以我受到了阻碍。我有这个HTML:

<section class="main-container">
    <ul class="landing-list">
        <li class="main-headings">
            <strong>SERVICES</strong><i class="icon icon-angle-down"></i>
            <div class="main-blurb" id="blurb-1">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus assumenda, in a quaerat iusto. Reiciendis consequuntur doloribus, sed tenetur aspernatur sunt perspiciatis. Odit non eos laudantium fuga officiis quia eius!</p>
            </div>
        </li>
        <li class="main-headings">
            <strong>WHY CHOOSE PMDS?</strong><i class="icon icon-angle-down"></i>
            <div class="main-blurb" id="blurb-2">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo rerum totam obcaecati at eligendi voluptate tempore aspernatur. Maxime accusantium nobis ab, at voluptatem porro, fugit sed sint fugiat sapiente vel?</p>
            </div>
        </li>
        <li class="main-headings">
            <strong>PORTFOLIO</strong><i class="icon icon-angle-down"></i>
            <div class="main-blurb" id="blurb-3">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio similique aut voluptates, facilis, provident quae cupiditate dolore nisi non accusamus quidem dolorem dicta aliquam, quod temporibus. Quas deleniti, aliquam ab.</p>
            </div>
        </li>
        <li class="main-headings">
            <strong>CONTACT</strong><i class="icon icon-angle-down"></i>
            <div class="main-blurb" id="blurb-4">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A, recusandae. Commodi, mollitia autem necessitatibus dicta. Explicabo quam harum, perferendis repellat vel aut, est fugit assumenda blanditiis ratione, doloribus molestiae consequuntur.</p>
            </div>
        </li>
    </ul>
</section>

我正在寻找的效果是,当单击其中一个.icons时,会显示其下方的.main-blurb,并隐藏所有其他.main-blurb。这是我写的js:

$('section ul li .icon').click(function() {
    var i = $(this).index();
    $('.main-blurb').hide();
    $('#blurb-' + (i+1)).show();
});

我把它放在.js文件中,并在我的application.js中需要它。当我运行它时,没有任何反应。我重新启动了服务器以及所有这些,我只是想知道是否有一些我缺少的语法。

3 个答案:

答案 0 :(得分:2)

var i = $(this).index();始终等于1,因为.icon是每个<li>中的第二个元素。

尝试:

$('section ul li .icon').click(function() {
    $('.main-blurb').hide();
    $(this).parent().find('.main-blurb').show();
});

答案 1 :(得分:1)

whitout所有代码很难知道发生了什么。 要获得标记i下方的下一个div,您可以使用jquery next()函数:

$('section ul li .icon').click(function() {
    //hide all divs with main-blurb classes
    $('.main-blurb').hide();
    //show next element with main.blurb class
    $(this).next('.main-blurb').show();
});

答案 2 :(得分:0)

我的问题是我对Javascript的无知。我忘了包括:

$(document).ready(function() {

在我的javascript文件的开头。现在一切正常!