我已经制作了一个由ajax驱动的类似按钮,我已经定义了一个刷新文本的功能。现在我想改变它以便从字体真棒fa-heart-o更新到fa-heart和反之。我该怎么做?见下面的代码
base.html文件
<script>
$(document).ready(function(){
function updateText(btn, newCount, iconClass, verb){
verb = verb || "";
$(btn).html(newCount + '<i class="' + iconClass + '"></i>' + verb )
btn.attr("data-likes", newCount)
}
$(".like-btn").click(function(e){
e.preventDefault()
var this_ = $(this)
var likeUrl = this_.attr("data-href")
var likeCount = parseInt(this_.attr("data-likes")) | 0
var addLike = likeCount + 1
var removeLike = likeCount - 1
if (likeUrl){
$.ajax({
url: likeUrl,
method: "GET",
data: {},
success: function(data){
console.log(data)
var newLikes;
if (data.liked){
updateText(this_, addLike, "fa fa-heart")
} else {
updateText(this_, removeLike, "fa fa-heart-o")
}
}, error: function(error){
console.log(error)
console.log("error")
}
})
}
})
})
</script>
和html按钮
<a class='like-btn' data-href='{{ comentario.get_api_like_url }}' data-likes='{{ comentario.likes.count }}'
href='{{ comentario.get_like_url }}'>{{ comentario.likes.count }}
{% if request.user in comentario.likes.all %}
<i class="fa fa-heart"></i>
{% else %}
<i class="fa fa-heart-o"></i>
{% endif %}
感谢您的帮助。
答案 0 :(得分:2)
在成功回调中,使用updateText定义元素。
示例强>
success: function(data) {
console.log(data)
var newLikes;
if (data.liked) {
updateText(this_, addLike, "fa fa-heart")
} else {
updateText(this_, removeLike, "fa fa-heart-o")
// remove one like
}
}, error: function(error) {
console.log(error)
console.log("error")
}
function updateText(btn, newCount, iconClass, verb) {
verb = verb || "";
$(btn).html(newCount + '<i class="fa' + iconClass + '"></i>' + verb)
btn.attr("data-likes", newCount)
}
答案 1 :(得分:1)