简体   繁体   中英

JQuery statement if/else not working on click function, runs if and else part

First I verify if the text of the element is "ocultar menu", if it's true, I change the text and add hide Class to some others elements. My intention is that the function breaks there, and see the value of text only in the start of the event, and no when I change it inside the function. But when I click once, it appears hide, very fast in the console of the browser, it's like the functions checks the value and continue to check and pass in the if and in the else part of the code. I used StopPropagation() but doesn't works and I've tried to change the on event to click and not worked too. Need Help, thanks.

   var $position = $("#ocult-menu").position();
    $("#ocult-menu").on("click",function(){ 
        var $text = $(this).find('p').text();
        if ($text == "ocultar menu"){
            $(".info").addClass("hide");
            $(".photo").addClass("hide");
            $(".map").addClass("hide");
            $(".similar").addClass("hide");
            $(".share").addClass("hide");
            $("#menu-single").offset({left: $position.left});
            $(".exibir").css("background-position","-1px 430px");
            $(this).find('p').text("exibir menu");
        }
        else if( $text == "exibir menu"){
            $(".info").removeClass("hide");
            $(".photo").removeClass("hide");
            $(".map").removeClass("hide");
            $(".similar").removeClass("hide");
            $(".share").removeClass("hide");
            $("#menu-single").offset({left: $position.left});
            $(this).find('p').text("ocultar menu");
        }
    });

好吧,我在站点上看到两次单击事件,如果我转到控制台并键入$(“#ocult-menu”)。click(),它将很好

You might be adding the onclick handler more than once, causing it to execute multiple times per click. Try adding some log statements, like so:

$("#ocult-menu").on("click",function(){ 
    console.log("onclick");
    ...
    if ($text == "ocultar menu"){
        console.log("text = ocultar menu");
        ...
    }
    else if( $text == "exibir menu"){
        console.log("text = exibir menu");
        ...
    }
});

If you see "onclick" being logged more than once, that's the problem. Then you can move this handler setup code to your initial one-time page load function.

$(function() {
    $("#ocult-menu").on("click",function(){
        ...
    });
});

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM