【发布时间】:2016-09-24 06:43:29
【问题描述】:
我想要做的是我有字形框,如果有通知,我希望该框根据通知的计数改变其颜色。我想我快到了,但它就是行不通。我检查了,但 CSS 没有通过。所以这就是我所做的。
我在导航栏中有这个
<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-inbox 需要随着计数改变颜色。
为了实现我有这个代码
<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;
}
如您所见,颜色应该是红色的,但它不起作用。我想我需要将用于 glyphicon-box 的#button 放在某个地方,但我不知道。另外,我不确定如何让 count 出现在框中。
如果我在控制台中使用$("#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>
我正在尝试让它像 Stack Overflow 一样,通知框会随着计数而改变颜色 - 这可能吗?
【问题讨论】:
-
在
$.ajax配置选项中使用dataType: 'json'或在success回调中使用JSON.parse()手动将字符串解析为JSON。 -
你得到了 console.log(count).. 的价值吗?
-
您是否检查过 data.count 是否有任何值。还尝试将您的 css 更改为仅 .notification 而不是 #notification_dropdown.notification
-
@Tushar 你能在答案中证明这一点吗?我一定会试试的
-
@DemoUser 是的,我看到了计数...只是不知道如何显示
标签: javascript jquery html css ajax