下面是我的简单代码,其中想要像 Gmail 样式的代码添加书签。
$(this).toggleClass('favorited');
上述声明不起作用。得到 ajax 响应后,star 不会变成黄色。但是如果你把上面的语句放在 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>