为几个点击事件创建一次元素

时间:2017-02-26 18:54:43

标签: javascript jquery html

我想用类创建一个div(只有一个)。每次扩展细节时都必须打开,但每次点击都会创建div ...

这是HTML

<main>
    <section>
        <h3>title</h3>

        <div>
            <details>
                <summary>sum1</summary>
                content1
            </details>

            <details>
                <summary>sum2</summary>
                content2
            </details>
        </div>

    </section>
</main>

这里是JS

$('.firstContent').hide();

$('details').click(function () {
    $(this).toggleClass("openedDetails");
    $('details').not(this).removeAttr("open");
    $('details').not(this).removeClass("openedDetails");

    if ($('details').hasClass('openedDetails')) {
        $('section h3').after('<div class="firstContent">content3</div>');
        $('.firstContent').show();
    } else {
        $('.firstContent').hide();
    }

});

编辑:使用toggleClass系统(我认为这是一种更好的方法),.firstContent div直接在h3和下一个div之间的HTML中创建

$('.firstContent').hide();
$('main details').click(function(){
    var mainSelf = $(this);
    $(mainSelf).toggleClass('openedDetails');
    $('details').not(mainSelf).removeAttr('open');
    $('details').not(mainSelf).removeClass('openedDetails');

    var mainParent = $(mainSelf).parents('main');
    mainParent.addClass('mainParent');
    $('main').not(mainParent).removeClass('mainParent');

    var openedFirst = $('.firstContent', mainParent);
    openedFirst.addClass('openedFirst');
    $('.firstContent').not(openedFirst).removeClass('openedFirst');
    openedFirst.show();
    $('.firstContent').not(openedFirst).hide();

});

1 个答案:

答案 0 :(得分:1)

使用remove()代替hide(),因为您基本上每次点击都会添加一个新的firstContent div,而不会移除上一个。你只是隐藏它。

$('.firstContent').hide();

$('details').click(function () {
$('.firstContent').remove();
    $(this).toggleClass("openedDetails");
    $('details').not(this).removeAttr("open");
    $('details').not(this).removeClass("openedDetails");

    if ($('details').hasClass('openedDetails')) {
        $('section h3').after('<div class="firstContent">content3</div>');
        $('.firstContent').show();
    } else {
        $('.firstContent').remove();
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
    <section>
        <h3>title</h3>

        <div>
            <details>
                <summary>sum1</summary>
                content1
            </details>

            <details>
                <summary>sum2</summary>
                content2
            </details>
        </div>

    </section>
</main>