Question

The problem is I would like to fire only once when the mouseevent function is triggered, e.g.

 $(document).ready(function() {
     $("#menu").click(function(){
         $('#menu_div').show();
         menu_function();
     });


     $("#menu_close").click(function(){
         $('#menu_div').hide();
     });
 });

function menu_function(){
    $(".select_li").live(
        "click",
        function() {
            alert("test");
        }
    );
}

The example has two objects, menu and menu close; when the menu press, the ui box is shown, and run the menu_function , which fires an alert test message. The problem is when the menu_close is clicked and box closed, and open it again, the alert test will fire twice. I observe that the times of div box close and open again is the same as the fire times of the function, how can I fix it?

If I would like not using unbind, are there any better solution?

Was it helpful?

Solution

Your menu_function() is NOT just firing an alert test message - it is adding a live click listener to everything in the DOM that has a class of "select_li" that fires a test alert. This means that every time you click on #menu you are adding ANOTHER listener to .select_li - so if you click #menu 10x, you should have 10 listeners for each click of .select_li.

If you are truly trying to JUST show an alert when you click on #menu, your menu_function() should only look like this:

function menu_function() {
    alert("test");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top