我想要做的是我有圖形框,如果有通知,我希望框中改變顏色與通知的計數。我想我幾乎在那裏,但它不會工作。我檢查過,但CSS沒有通過。所以這就是我所做的。爲什麼這不是AJAX功能改變顏色?
我有這樣的導航欄
<li class="dropdown">
<a href="#" class="dropdown-toggle notification-toggle" data-toggle="dropdown" role="button" aria-expanded="false" id="button">
<span class='glyphicon glyphicon-inbox' aria-hidden="true"></span>
<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu" id='notification_dropdown'>
</ul>
</li>
所以glyphicon-收件箱需要改變其顏色與計數。
爲了實現這個目標我有這樣的代碼
<script>
$(document).ready(function(){
$(".notification-toggle").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "{% url 'get_notifications_ajax' %}",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
$("#notification_dropdown").html(' <li role="presentation" class="dropdown-header">Notifications</li>');
var count = data.count
console.log(count)
if (count == 0) {
$("#notification_dropdown").removeClass('notification');
var url = '{% url "notifications_all" %}'
$("#notification_dropdown").append("<li><a href='" + url+ "'>View All Notifications</a></li>")
} else {
$("#notification_dropdown").addClass('notification');
$(data.notifications).each(function(){
var link = this;
$("#notification_dropdown").append("<li>" + link + "</li>")
})
}
console.log(data.notifications);
},
error: function(rs, e) {
console.log(rs);
console.log(e);
}
})
})
})
</script>
如果通知計數== 0,我有
$("#notification_dropdown").removeClass('notification');
其他
$("#notification_dropdown").addClass('notification');
而對於CSS我有這個
#notification_dropdown{
}
#notification_dropdown.notification{
background-color: red;
}
正如你所看到的顏色應該是紅色的,但它並沒有把戲。我想我需要將#button放置在某個地方的glyphicon-box,但我不知道。另外,我不確定如何在框中顯示計數。
如果我在控制檯使用$("#notification_dropdown")
我得到
<ul class="dropdown-menu notification" role="menu" id="notification_dropdown"> <li role="presentation" class="dropdown-header">Notifications</li><li><a href="/notifications/164/?next=/post/test0/">content</a></li><li><a href="/notifications/165/?next=/post/test0/">content</a></li></ul>
我試圖使它像堆棧溢出,通知框中改變顏色與它的數量 - 這可能嗎?
使用'數據類型:「json''在'$ .ajax'配置選項或者在'success'回調中使用'JSON.parse()'手動將字符串解析爲JSON。 – Tushar
你是否爲console.log(count)..獲得了價值? –
你檢查了data.count是否有任何價值。也嘗試改變你的CSS只有.notification而不是#notification_dropdown.notification – brk