简体   繁体   English

jquery函数只工作一次?

[英]jquery function only working once?

I have this function that is suppose to change the html of a span. 我有这个函数,假设改变跨度的html。 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代码

<?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. 你的javascript中有一个拼写错误,你已经把vailspan放在if(msg === "available") { line后面的availspan

If it's not that, try changing the click event to a live one: 如果不是这样,请尝试将click事件更改为live事件:

$('#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 以防你的javascript覆盖#availabilityicon图标元素并且无法将事件重新附加到新的

The "availabiltyicon" you click is being replaced with another with the same name. 您单击的“availablebiltyicon”将被另一个具有相同名称的替换。 You can try using .live() or you can read up on event delegation. 您可以尝试使用.live(),也可以阅读事件委派。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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