Layer/jquery获取父窗口的元素

一、描述

  • 如图,我们要在 消息中心 选项卡中 改变 消息提示框(铃铛)旁边的未读消息数量
    在这里插入图片描述

二、分析

<!-- 未读消息数 -->
<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获取父窗口的元素

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);

猜你喜欢

转载自blog.csdn.net/qq_36025814/article/details/109057207