Gmail Star就像使用jQuery进行书签一样

时间:2013-04-20 18:43:52

标签: php javascript jquery ajax

我正在尝试使用jQuery创建一个像书签这样的明星。不幸的是,我所拥有的只是单向工作。这意味着,如果一个链接是未加星标的,那么它就会成功加星,但是如果一个链接已经加星标并且我想要取消它,那么星形图像会从页面中完全消失,但是在后端它确实有效,但在前端是明星图像完全消失。

我的HTML中有以下内容:

require_once('connection.inc.php');
$con = dbConnect('read');
$sql = "SELECT * FROM trn_bookmark";
$result = $con->query($sql) or die(mysqli_error());
while($row = $result->fetch_assoc()) {
    $className  = "star";
    if($row['bookmark_flag'] == 'Y'){
        $className = "favorited";
    }
    echo '<div id="'.$row['bookmark_id'].'"><a href="javascript:void(0);" class="'.$className.'"></a> <span>'.$row['bookmark_desc'].'</span></div>';
}

CSS:

.star {
background-color: transparent;
background-image: url('star-off.png');
background-repeat:no-repeat;
display: block;  
height:16px;
width:16px;
float:left;
}
.favorited {
 text-indent: -5000px;
background-color: transparent;
background-image: url('star-on.png');
background-repeat:no-repeat;   
height:16px;
width:16px;
float:left;
}

JavaScript函数是这样的:

$(document).ready(function(){   
 $('.star,.favorited').click(function() {
        var id = $(this).parents('div').attr('id');             
        var className = $(this).attr('class');
        var flag  = (className=='star') ? 'Y':'N';
        var $this = $(this);
        $.ajax({
                type: "post",
                url: "conversation.php",
                cache: false,               
                data:{'bookmarkId': id,'flag':flag},
                success: function(response){
                    if(response=='true'){                               
                        $this.toggleClass("favorited");
                    }   
                },
                error: function(){                      
                    alert('Error while request..');
                }
             });
  });
});

和conversation.php:

$bookmarkId = $_POST['bookmarkId'];
$flag = $_POST['flag'];
require_once('connection.inc.php');
$con = dbConnect('read');
$stmt = $con->stmt_init();
$sql = "UPDATE trn_bookmark SET bookmark_flag = ? WHERE bookmark_id = '$bookmarkId'";
    if ($stmt->prepare($sql)) {
        $stmt->bind_param('s', $flag);
        $done = $stmt->execute();
    }

    echo 'true';

我上传了它,以便您可以看到正在发生的事情。您可以在此链接中查看此处发生的情况:http://www.rytenet.com/starrating/index.php

1 个答案:

答案 0 :(得分:2)

试试这个

如果明星是最喜欢的页面加载,则存储$ className =“favorited”而不是className =“star favorited”

while($row = $result->fetch_assoc()) {
    $className  = "star";
    if($row['bookmark_flag'] == 'Y'){
        $className .= " favorited";
    }
    echo '<div id="'.$row['bookmark_id'].'"><a href="javascript:void(0);" class="'.$className.'"></a> <span>'.$row['bookmark_desc'].'</span></div>';
}