晚上好,我无法运行此代码:在实践中,您添加新类但不删除旧类。这是一个喜欢和不喜欢的简单系统
$query2 = mysql_query("SELECT * FROM totlike WHERE id_user_like = $id_user AND id_post_like = ". $risultato['id']."");
if (mysql_num_rows($query2) == 1) {
$like = '<i class="glyphicon glyphicon-heart" id="'. $risultato['id'] .'"></i>';
} else {
$like = '<i class="glyphicon glyphicon-heart-empty" id="'. $risultato['id'] .'"></i>';
}
var elem = $('#' + id_post).attr('class');
if (elem == "glyphicon glyphicon-heart") {
$('#' + id_post).removeClass('glyphicon glyphicon-heart').addClass('glyphicon glyphicon-heart-empty');
} else {
$('#' + id_post).removeClass('glyphicon glyphicon-heart-empty').addClass('glyphicon glyphicon-heart');
}
答案 0 :(得分:1)
我已经清理了一些代码,但通常看起来很好。我不确定这是否会有所帮助,但下面的代码段显示它运行正常。
function toggleHeart(id_post) {
var element = $('#' + id_post);
if (element.hasClass("glyphicon-heart")) {
element.removeClass('glyphicon-heart');
element.addClass('glyphicon-heart-empty');
} else {
element.removeClass('glyphicon-heart-empty');
element.addClass('glyphicon-heart');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<p>Click on the button or heart to toggle</p>
<i class="glyphicon glyphicon-heart" id="1" onClick="toggleHeart(1)">1</i>
<button onClick="toggleHeart(1)">Toggle</button>
<br />
<i class="glyphicon glyphicon-heart-empty" id="2" onClick="toggleHeart(2)">2</i>
<button onClick="toggleHeart(2)">Toggle</button>