简体   繁体   中英

How to execute two functions using toggle in jquery?

I used toggle() function for executing two functions. When I click the image with class="favourite", on first click, the first function must be executed and I should get the alert('test1') and for second click, the second function must be executed and I should get the alert('test2') and the execution must stop there.

My problem is that, When the image is clicked for the second time, I am getting alert('test2') followed by alert('test1'), only second function should be executed for second click ie I should get only alert('test2') on second click. How to stop the execution of the first function on second click?

This is my jquery code in index.phtml file:

jqry("#wrap").delegate('img.favourite','click',function(){ 
    var id = jqry(this).attr('pid');
    jqry('#'+id).toggle(function(){
            alert('test1');     
        },
        function(){
            alert('test2');
        }
    );
});

This is my code in JS file

    <img class="favourite"  src="images/fav.png" alt="favourite" pid ='project_id'>

The output I am getting on first click is test1

The output I am getting on second click is test2 test1

On second click I should get the output alert test2 and stop the execution, but it is further executing the previous function and giving both the alerts ie test2 followed by test1 . How can I solve this?

The form of .toggle() that you are using was deprecated in jQuery 1.8 and removed in 1.9. In addition, it binds a click handler each time it is called so you really don't want to be calling it multiple times which is probably why you see two alerts because each time you bind it, you get one more callback on a click. First one, then two, then three, etc...

I'd suggest you find a different way of alternating functions on each click. Perhaps just set a flag on the item with .data() and alternate based on the flag.

It's not exactly clear what you're trying to do with the .toggle() function on the id element, but this will get you alternating function calls and you can then implement whatever you want in each function:

jqry("#wrap").delegate('img.favourite', 'click', function() { 
    var toggle = $(this).data("toggleFlag") || false;
    var id = jqry(this).attr('pid');
    if (toggle) {
         // do whatever you want with id here
         alert("test1");
    } else {
         // do whatever you want with id here
         alert("test2");
    }
    // reverse the toggle flag
    $(this).data("toggleFlag", !toggle);
});

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