一、描述
- 如图,我们要在
消息中心
选项卡中 改变消息提示框(铃铛)
旁边的未读消息数量
。
二、分析
- 未读数量 html 代码,参考地址 Layui官方文档 - 页面元素 - 徽章
<!-- 未读消息数 -->
<span class="layui-badge" style="display: none" id="not-read-msg-count"></span>
由于 消息提示框(铃铛图标)
属于header
,消息中心
选项卡 属于content
模块,直接查找元素再赋值
肯定是不行
的。
- 错误案例 - 直接查找
$.ajax({
url: '/././.',
type: 'post',
success: function(res) {
let notRead = res.data;
if(notRead > 0){
//直接找到元素,显示 - 赋值
$('#not-read-msg-count').show();
$('#not-read-msg-count').text(notRead);
}else{
//无消息,直接隐藏元素
$('#not-read-msg-count').hide(); //元素隐藏
}
},
error: function(res) {
console.log(res.msg);
}
});
- 正确案例 - 在父窗口查找
$.ajax({
url: '/././.',
type: 'post',
success: function(res) {
let notRead = res.data;
if(notRead > 0){
//在父窗口中找到元素,显示 - 赋值
$('#not-read-msg-count', window.parent.document).show();
$('#not-read-msg-count', window.parent.document).text(notRead);
}else{
//无消息,隐藏父窗口中的元素
$('#not-read-msg-count', window.parent.document).hide(); //元素隐藏
}
},
error: function(res) {
console.log(res.msg);
}
});
三、参考
Jquery写法:("#父窗口元素ID",window.parent.document);
Javascript写法:window.parent.document.getElementByIdx_x("父窗口元素ID");
取父窗口的元素方法:$(selector, window.parent.document);
那么你取父窗口的父窗口的元素就可以用:$(selector, window.parent.parent.document);
类似的,取其它窗口的方法大同小异
$(selector, window.top.document);
$(selector, window.opener.document);
$(selector, window.top.frames[0].document);