문제

I have a toggle list that is used for selection. The problem is that sometimes, the click event on the li elements is fired twice. The toggle on the .config div works fine, but as it's the parent of the list I thought there may be something there. Anyone got an idea of what could be going on here?

HTML:

<div class="config">
    <div class="select-list hidden">
        <ul>
            <li>Something 1</li>
            <li>Something 2</li>
            <li>Something 3</li>
        </ul>
    </div>
</div>

jQuery:

$('body').on('click', '.config', function(e) {
    if (e.target == this) {
        $(this).find('.select-list').toggleClass('hidden');
    } else {
        e.stopPropagation();
    }
});

$('body').on('click', '.select-list li', function() {
    $(this).toggleClass('selected');
});
도움이 되었습니까?

해결책

Change your second chunk of code to:

$('body').on('click', '.select-list li', function(e) {
    e.stopPropagation();
    $(this).toggleClass('selected');
});

When you click the list item, the click event is bubbling up the DOM to the .config div and triggering the click event on it, causing the toggleClass to occur again.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top