Domanda

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');
});
È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top