我添加到产品的愿望列表中。(django项目)如果用户将一个产品添加到这个列表中,就点击一个心形图标。如果用户已经将此产品添加到列表中,则心图标为红色,如果此产品不在用户收藏夹列表中,则心图标为白色。每次移除或将图标添加到列表中时,我都想更改图标的颜色。在我写的代码中,这个操作只做一次,如果它同时再次点击,颜色不会有任何变化。
{% if request.user in product.favourite.all %}
<a href="{% url 'home:favourite' product.id %}"
class="favourite-product fa-btn{{ product.id }}"
data-id='{{ product.id }}' data-text="remove">
<i class="fa fa-heart test{{ product.id }}" style="color:red"></i></a>
{% else %}
<a href="{% url 'home:favourite' product.id %}"
class="favourite-product fa-btn{{ product.id }}"
data-id='{{ product.id }}' data-text="add">
<i class="fa fa-heart test{{ product.id }}" style="color:#eee;"></i></a>
{% endif %}
# ajax
$(document).on('click', '.favourite-product', function (e) {
e.preventDefault();
const likeText = $(`.fa-btn${product_id}`).attr("data-text");
const trim = $.trim(likeText)
$.ajax({
url: $(this).attr('href'),
type: 'GET',
data: {
'product': product_id
},
success: function (response) {
if (trim === 'add') {
$(`.test${product_id}`).css({"color": "red"});
} else {
$(`.test${product_id}`).css({"color": "#eee"});
}
},
error: function (response) {
alert("error");
}
});
});
可以使用selector.data(“text”,“remove”)
更改data-atr值的文本。此外,您还可以使用$(this)
,其中$(this)
引用a
标记,单击该标记可获得数据(“text”)
以及数据(“id”)
的值,然后将其传递给ajax调用。
演示代码:
null
$(document).on('click', '.favourite-product', function(e) {
e.preventDefault();
var selector = $(this)
var data_id = $(this).data("id") //to get data attr
var likeText = $(this).data("text"); //get text
var trim = $.trim(likeText)
console.log(data_id + " " + likeText)
/*$.ajax({
url: $(this).attr('href'),
type: 'GET',
data: {
'product': data_id //pass data_id
},
success: function(response) {*/
//compare
if (trim === 'add') {
//change i colour
selector.find("i").css({
"color": "red"
});
//change text
selector.data("text", "remove")
} else {
///same as above
selector.find("i").css({
"color": "#eee"
});
selector.data("text", "add")
}
/* },
error: function(response) {
alert("error");
}
});*/
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="{% url 'home:favourite' product.id %}" class="favourite-product fa-btn1" data-id='1' data-text="remove">
<i class="fa fa-heart test1" style="color:red"></i></a>
<a href="{% url 'home:favourite' product.id %}" class="favourite-product fa-btn2" data-id='2' data-text="add">
<i class="fa fa-heart test2" style="color:#eee"></i></a>