简体   繁体   中英

jquery function only working once?

I have this function that is suppose to change the html of a span. It works the first time but anyclick after that it doesn't change anything. I know the query is working because the database is updating. Here's the code.

$('#availabilityicon').click(function() {
    $.ajax({
            type: "GET",
            url: "includes/changeavailability.php",
            success: function(msg) {
                    if(msg === "available") {
                            var vailspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/available.png" /></a>');
                    }
                    else if(msg === "unavailable") {
                            var availspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/unavailable.png" /></a>');
                    }
            }
    });
});

here is the php code

<?php
session_start();
$user = $_SESSION['username'];
include("dbcon.php");
$result = mysql_query("SELECT availability FROM user WHERE username='$user' ORDER BY id DESC") or die(mysql_error());
$row = mysql_fetch_assoc($result);
$availability = $row['availability'];
if($availability == 'yes') { 
$query = mysql_query("UPDATE user SET availability='no' WHERE username='$user'") or die(mysql_error());
echo "unavailable"; 
}
elseif($availability == 'no' or $availability == "") { 
$query = mysql_query("UPDATE user SET availability='yes' WHERE username='$user'") or die(mysql_error()); 
echo "available"; 
}
mysql_close($con);
?>

There's a spelling mistake in your javascript, you've put vailspan where you probably meant to put availspan after the if(msg === "available") { line.

If it's not that, try changing the click event to a live one:

$('#availabilityicon').live('click', function() {

just in case your javascript is overwriting that the #availabilityicon icon element and failing to re-attach the event to the new one

The "availabiltyicon" you click is being replaced with another with the same name. You can try using .live() or you can read up on event delegation.

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