简体   繁体   中英

Javascript function won't run twice

I have a Jvascript function that when an image is clicked a php file is run and the image that was clicked updates. I made the another function that changes the image back if pressed again. But after running the first function, if you click the image again, nothing is happening. These are my functions:

<script>
    function upvote(id,bruger_id)
    {
        $.get("scripts/upvote.php?id="+id+"&bruger_id="+bruger_id, function() {
            // Update image
            $('.changeUp').attr('src', 'images/up.png');
            return;
        });
    }

    function noUpvote(id,bruger_id)
    {
        $.get("scripts/removevote.php?id="+id+"&bruger_id="+bruger_id, function() {
            // Update image
            $('.removeUp').attr('src', 'images/neutral_up.png');
            return;
        });
    }
</script>

This is where I call the functions. The base image shown is based on cookies.

<img class="changeUp" 
    onclick="upvote('.$feed[$loaded]["id"].','.$feed[$loaded]["bruger_id"].');" 
    src="images/neutral_up.png" width="20px">

I realized the error is that it simply calls the same function again and so the image doesn't change back. But how can I work around this then?

Try this:

function upvote(id,bruger_id)
     {
         $.get("scripts/upvote.php?id="+id+"&bruger_id="+bruger_id, function() {
            $('.changeUp').attr('src', 'images/up.png');
            $('.changeUP').attr('onclick', 'noUpvote('.$feed[$loaded]["id"].','.$feed[$loaded]["bruger_id"].');');
         });
     }

    function noUpvote(id,bruger_id)
    {
         $.get("scripts/removevote.php?id="+id+"&bruger_id="+bruger_id, function() {
            $('.changeUP').attr('src', 'images/neutral_up.png');
            $('.changeUP').attr('onclick', 'upvote('.$feed[$loaded]["id"].','.$feed[$loaded]["bruger_id"].');');
         });
    }

I think the problem is that in your first method, upvote() , you are using a class selector with changeUp but you never change the class of the img tag with jQuery, then when you call the second method, with class selector removeUp , there is nothing with that class, try this:

function upvote(id, bruger_id)
{
  $.get("scripts/upvote.php?id="+id+"&bruger_id="+bruger_id, function() {
    $('.changeUp').attr('src', 'images/up.png');
    $('.changeUp').removeClass('changeUp').addClass('removeUp');
  }
}

Your img will be something like this:

<img class="removeUp" ...>

And you can call the second method and change the src attribute.

Greetings.

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