下面是我的簡單代碼,其中想要爲Gmail樣式的代碼添加書籤。toggleClass在ajax案例中無法正常工作
$(this).toggleClass('favitedited');
以上聲明不起作用。得到ajax響應後,明星不會變成黃色的。 但如果你把上面的語句放在ajax塊之外,它就可以工作。不能理解爲什麼會發生。
<html>
<head>
<style>
.star {
background-color: transparent;
background-image: url('http://www.technicalkeeda.com/img/images/star-off.png');
background-repeat:no-repeat;
display: block;
height:16px;
width:16px;
float:left;
}
.star.favorited {
text-indent: -5000px;
background-color: transparent;
background-image: url('http://www.technicalkeeda.com/img/images/star-on.png');
background-repeat:no-repeat;
height:16px;
width:16px;
float:left;
}
span{
color: #2864B4;
}
</style>
<script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script>
$(document).ready(function(){
$('.star').click(function() {
var id = $(this).parents('div').attr('id');
$.ajax({
type: "post",
url: "http://www.technicalkeeda.com/demos/bookmark",
cache: false,
data:{'bookmarkId': id},
success: function(response){
alert('response' +response);
if(response=='true'){
$(this).toggleClass('favorited');
}else{
alert('Sorry Unable bookmark..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
</script>
</head>
<body>
<div id="1000"><a href="javascript:void(0);" class="star" ></a><span>Php CodeIgniter Server Side Form Validation Example</span></div>
<div id="2000"><a href="javascript:void(0);" class="star"></a><span>Live Search Using Jquery Ajax, Php Codeigniter and Mysql</span></div>
<div id="3000"><a href="javascript:void(0);" class="star"></a><span>Voting system Using jQuery Ajax and Php Codeigniter Framework</span></div>
</body>
</html>
是的,如果你硬編碼響應爲真,仍然不能正常工作 – Vicky 2013-02-27 02:19:56