开发者

jQuery toggleClass not working?

开发者 https://www.devze.com 2023-01-22 21:18 出处:网络
Very simply put : the line c开发者_C百科urrentItem.toggleClass(\'open\'); doesn\'t seem to work.

Very simply put : the line c开发者_C百科urrentItem.toggleClass('open'); doesn't seem to work.

More precisely, when inspecting the results with firebug, I can see the class "open" flashing (appearing and immediately disappearing) on the relevant element. So it's like the function is actually triggered twice (of course I only click once).

Can somebody explain me why this is and how to prevent it?

Here is my jQuery code :

$('div.collapse ul.radio_list li input[type=radio]').click(function (event) {

    var currentTree = $(this).parent().parent().parent();
    var currentItem = $(this).parent().parent();
    var currentGroup = currentItem.attr('rel');

    $(this).parents('ul').children('li').removeClass('select');
    if ($(this).is(':checked')) {
        currentItem.addClass('select');
    }

    currentItem.toggleClass('open');

    var currentLevel = 0;
    if (currentItem.is('.level1')) {currentLevel = 1;}
    if (currentItem.is('.level2')) {currentLevel = 2;}
    if (currentItem.is('.level3')) {currentLevel = 3;}
    var nextLevel = currentLevel + 1;

    currentTree.children('li').filter('li[rel ^=' + currentGroup + '].level' + nextLevel).animate({'height': 'show', 'opacity': 'show'}, 250).addClass('currentChild');
});

And here is a part of my HTML code, slightly simplified for better readability (not very pretty I know, but I only have a limited control on the HTML output) :

<div class="col_left collapse">
    <ul class="radio_list" rel="7">
        <li class="onglet level0" rel="group1">
            <span class="onglet level0">
                <input type="radio" />
                    <label>Services Pratiques</label></span>
            <input type="hidden" value="1">
        </li>

Thanks in advance.


Problem solved: the JS file was actually included twice in the HTML head, which caused the function to be triggered twice with each click.


I had a similar problem on my site, and I found that I had accidently duplicated the toggleclass hook all the way at the bottom, when first messing around with it. Oops! Make sure to look for double calls!


I had a similar problem doing this:

html:

<a>JS-link</a>

js:

$('a').click(function(event) {
    ... my stuff ...
    # Forgot to do event.preventDefault(); !!
}

results in clicks being register twice!


I had the same issue and realized I had accidentally bound the function twice. I had originally meant to move the code from one javascript file to another but accidentally left the original in its place.

0

精彩评论

暂无评论...
验证码 换一张
取 消