[英]Why this isn't this AJAX function changing color?
我想要做的是我有字形框,如果有通知,我希望框根据通知的计数改变其颜色。 我想我快到了,但它只是行不通。 我检查过,但 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 放在某个地方,但我不知道。 另外,我不确定如何使计数出现在框中。
如果我在控制台中使用$("#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 一样,通知框随着计数改变颜色 - 这可能吗?
要更改字形的颜色 - 您需要更改颜色属性而不是背景:
#notification_dropdown.notification{
color: red;
}
整个 html 中是否存在具有相同 ID 'notification_dropdown' 的元素? 请检查 html 并通过此 ID 查找。 它可能是隐藏的形式。 在这种情况下,css 可能会应用于该隐藏元素而不是该可见元素。
如果是,请尝试:
$("#notification_dropdown:visible").removeClass('notification');
或者
$("#notification_dropdown:visible").addClass('notification');
尝试这个:
setTimeout(function(){
$("#notification_dropdown:visible").addClass('notification');
}, 2000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.