iframe的顶部/主窗口中的jQuery hide/访问元素



我正在使用一个无法控制系统生成的HTML的CRM系统。这是我要处理的HTML标记的最简单形式。

<button id="cmdedit">Edit</button>
<textarea cols="30" rows="10"> Hi there </textarea>
<iframe src="s_blank.html" frameborder="0"></iframe>

我想在页面加载后隐藏cmdedit <button>。我只能更改该<textarea>的内容,然后将其插入DOM作为页面加载中以下<iframe>的HTML内容。我可以包括<script>标签,并编写进入该<iframe>的JQuery语句或JQuery语句,而JavaScript警报语句正常工作。我尝试使用以下代码隐藏<button>,但在页面加载后都没有工作。

脚本IFRAME:

<script type="text/javascript">
     $(document).ready(function(){         
        var MyRoleList = "@me.rolelist@";
        if (MyRoleList.indexOf(",9875,") > -1){         
            alert('aaa');   
            $('#cmdedit').hide();     
        }
     });
  </script>

系统生成完整的HTML

<html lang="en"><head>
    <title>Examinee Notice</title>
    <link rel="icon" type="image/x-icon" href="/images/favicon.ico">
	<link rel="SHORTCUT ICON" href="/images/favicon.ico">
	<link rel="stylesheet" type="text/css" href="/css/ccss/styles_common_basic_404048.css?version=201711.05">
    <link rel="stylesheet" type="text/css" media="screen" href="/jquery/jquery-confirm-master/css/jquery-confirm.css?v=201711.05">
    <script language="JavaScript" src="/jquery/jquery.js?v=201711.05"></script><style></style>
    <script type="text/javascript" src="/jquery/jquery-confirm-master/dist/jquery-confirm.min.js?v=201711.05"></script>
    <script type="text/javascript" language="JavaScript" src="/Ajax/uta/uta.js?v=201711.05"></script>
    <script type="text/javascript" language="JavaScript" src="/js/ssvalidate.js?v=201711.05"></script>
    <script type="text/javascript" src="/js/ssfieldfunctions.js?v=201711.05"></script>
    <script type="text/javascript" src="/js/ssfunctions.js?v=201711.05"></script>
    <script language="javascript">
        var _iseditmode=false;
            function jqueryalert(msg, confirmfn) {
                $.confirm({
                    title: "Hey Muhammad",
                    content: msg,
                    icon: 'fa fa-exclamation-triangle',
                    theme: 'material',
                    animation: 'scale',
                    closeAnimation: 'scale',
                    type: 'orange',
                    buttons: {
                        confirm: {
                            text: "OK",
                            btnClass: 'btn-orange',
                            keys: ['enter'],
                            action: function() {
                                if (confirmfn) {
                                    confirmfn();
                                }
                            }
                        }
                    }
                });
            }
            function jqueryconfirm(msg, confirmfn, cancelfn) {
                $.confirm({
                    title: "Hey Muhammad",
                    content: msg,
                    icon: 'fa fa-exclamation-triangle',
                    theme: 'material',
                    animation: 'scale',
                    closeAnimation: 'scale',
                    type: 'orange',
                    buttons: {
                        confirm: {
                            text: "Yes",
                            btnClass: 'btn-orange',
                            action: function() {
                                if (confirmfn) {
                                    confirmfn();
                                }
                            }
                        },
                        cancel: {
                            text: "No",
                            action: function() {
                                if (cancelfn) {
                                    cancelfn();
                                }
                            }
                        }
                    }
                });
            }
            function jqueryprompt(msg, confirmfn, cancelfn) {
                $.confirm({
                    title: "Hey Muhammad",
                    content: msg,
                    icon: 'fa fa-exclamation-triangle',
                    theme: 'material',
                    animation: 'scale',
                    closeAnimation: 'scale',
                    type: 'orange',
                    buttons: {
                        confirm: {
                            text: "Continue",
                            btnClass: 'btn-orange',
                            keys: ['enter'],
                            action: function() {
                                if (confirmfn) {
                                    if (!confirmfn(this.$content)) {
                                        return false;
                                    }
                                }
                            }
                        },
                        cancel: {
                            text: "Cancel",
                            keys: ['esc'],
                            action: function() {
                                if (cancelfn) {
                                    cancelfn();
                                }
                            }
                        }
                    }
                });
            }
        function no_error()
        { return true; }
        //window.onerror=no_error;
        function getsrc()
        { var frm=window.frames["page_win"].document.forms[0];
            if(frm==null) return "";
            var valuestr='n var frm_inp=document.forms[0];n';
            var ctltype;
            for (var i=0;i<frm.elements.length;i++)
            { ctltype=frm.elements[i].type.toLowerCase();
                if(ctltype=='radio'||ctltype=='checkbox')
                { if (frm.elements[i].checked)
                        valuestr+='nfrm_inp.elements['+i+'].checked=true;';
                }
                else
                    valuestr+='nfrm_inp.elements['+i+'].value=decodeURIComponent("'+encodeURIComponent(frm.elements[i].value)+'");';
            }
            return valuestr;
        }
        function puttxt()
        {
            window.frames["page_win"].document.writeln(document.frmtext.txt.value);
            window.frames["page_win"].document.close();
            var cmd=document.getElementById('cmdprint');
            if(cmd!=null)
                cmd.style.display="inline";
            cmd=document.getElementById('cmdemail');
            if(cmd!=null)
                cmd.style.display="inline";
            cmd=document.getElementById('cmdpdf');
            if(cmd!=null)
                cmd.style.display="inline";
            
            cmd=document.getElementById('cmddocx');
            if(cmd!=null)
                cmd.style.display="inline";
            
            cmd=document.getElementById('cmdemailpdf');
            if(cmd!=null)
                cmd.style.display="inline";
            cmd=document.getElementById('cmdemaildoc');
            if(cmd!=null)
                cmd.style.display="inline";
            if (window.frames["page_win"]!=null && window.frames["page_win"].ss_load)
                window.frames["page_win"].ss_load();
            if(window.frames["page_win"]!=null)window.frames["page_win"].focus();
        }
        function editdoc(button)
        {
            if(!_iseditmode)
            {window.frames["page_win"].location.href='/s_editor.html';
                button.value="Preview";
                _iseditmode=true;
            }else
            {  document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();
                window.frames["page_win"].document.writeln(document.frmtext.txt.value);
                window.frames["page_win"].document.close();
                button.value="Edit";
                _iseditmode=false;
            }
            switchbut(button.form,'cmdprint');
            switchbut(button.form,'cmdnewin');
            switchbut(button.form,'cmdemail');
            switchbut(button.form,'cmdemailpdf');
            switchbut(button.form,'cmdemaildoc');
            switchbut(button.form,'cmdpdf');
            switchbut(button.form,'cmdsavehtml');
            switchbut(button.form,'cmdsavepdf');
            switchbut(button.form,'cmdsavedoc');
            if ($('#functable').css("display") == "none")
                $('#functable').css("display", "table");
            else
                $('#functable').css("display", "none");
        }
        function switchbut(frm ,ctl)
        { var octl =frm.elements[ctl];
            if (octl!=null)
            {
                octl.disabled=!octl.disabled;
                if (octl.disabled)
                    $('[name="'+ctl+'"]').css("display", "none");
                else
                    $('[name="'+ctl+'"]').css("display", "inline");
            }
        }
        function CheckIsIE()
        {
            return (navigator.appName.toUpperCase().indexOf('MICROSOFT')>-1) ;
        }
        function printdoc()
        {
            if (CheckIsIE() == true)
            {
                document.page_win.focus();
                document.page_win.print();
            }
            else
            {
                window.frames['page_win'].focus();
                window.frames['page_win'].print();
            }
        }
        function savelocal(fname)
        {
            window.frames["page_win"].document.execCommand('SaveAs',null,fname)
        }
        function saveserver(type)
        { 
            if(_iseditmode) {
                document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();
            }
            var frm=document.frmtext;
            frm.filename.value=frm.filename.value.replace(/.html/,"");
            frm.filename.value=frm.filename.value.replace(/.pdf/,"");
            if(frm.mfolderid.value=='') {
                alert("Please select a folder name to save to.");
                return false;
            }
            
            var html = "<div class="form-group" style="text-align:center"><div style="margin:5px">Please enter a file name.</div><input class="Large" type="text" placeholder="File Name" class="form-control" id="filenameprompt" value="" + frm.filename.value + ""/></div>";
            jqueryprompt(html, function(promptobj) {
                var frm = document.frmtext;
                var newf = promptobj.find("#filenameprompt").val();
                if (newf == '') {
                    alert("File name cannot be empty.");
                    return false;
                } else if (!isValidFileName(newf)) {
                    alert("File name contains invalid characters (;,#,=,?)");
                    return false;
                }
                frm.filename.value=newf.replace(/s|/|\/g,'_');
                saveserversb(type)
                return true;
            });
            
        }
        function saveserversb(type) {
            
            saveserversb2(type);
            
        }
        function saveserversb2(type) {
            var frm=document.frmtext;
            var id=frm.mfolderid.value;
            if (id.indexOf('-')>0) {
                frm.objectid.value=id.substring(0,id.indexOf('-'));
                frm.folderid.value=id.substring(id.indexOf('-')+1);
            } else {
                frm.folderid.value=frm.mfolderid.value;
            }
            frm.action='s_savetextfile.jsp?type='+type;
            frm.target='page_win';
            frm.submit();
        }
    function newwind(frm)
    { var src;
        if(_iseditmode)
            src=window.frames["page_win"].oCKeditor.getData();
        else
            src=frm.txt.value;
        OpenWindow=window.open("", "newwin", "menubar=yes,scrollbars=yes,width=550,height=300,status=no,resizable=yes,dependent=yes,alwaysRaised=yes");
        OpenWindow.document.write(src);
        OpenWindow.document.close()
    }
    function newwinda()
    {
        var frm = document.frmtext;
        var inf = frm.txt.value;
        win = window.open("", "newwina", "menubar=yes,scrollbars=yes,width=650,height=500,status=no,resizable=yes,dependent=yes,alwaysRaised=no");
        win.document.write("" + inf + "");
        win.document.close();
    }
    function gotohcai()
    {   alert('When submitting to HCAI, please be aware that the submission time frame can vary between 0-120 min. If your submission is surpassing this time frame, please notify SmartSimple Support.', function() {
            location.href="/Apps/Bridge/hc_submissions.jsp?fieldid=1274403&entity=24&objectid=1127956&appid=102946";
        });
    }
    function gotosignority() {
        showsave("Load in Progress");
        location.href="/Apps/Bridge/sg_signority.jsp?fieldid=1274403&entity=24&objectid=1127956&appid=102946&codedid=QHJrJ0keIhgKFlALJGc1KgRXEAcuXRsTH2JcU0VNZl8~&islb=0&exportpdf=0&ismwin=0";
    }
        function emailpdf() {
            if(_iseditmode)
                document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();
            var frm=document.frmtext;
            frm.body.value=frm.txt.value;
            
            emailpdfsb();
            
        }
        function emailpdfsb() {
            var frm=document.frmtext;
            window.open("", "comp_win", "menubar=yes,scrollbars=yes,width=550,height=300,status=no,resizable=yes,dependent=yes,alwaysRaised=yes");
            frm.action="/Comm/ms_makepdf.jsp";
            frm.target='comp_win';
            frm.submit();
        }
    function pdfwrite(frm)
    {if(_iseditmode)
            document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();
        var frm=document.frmtext;
        new_win = window.open('','new_win', 'menubar=no,scrollbars=yes,width=600,height=340,status=no,resizable=yes,top=200,left=200,dependent=yes,alwaysRaised=yes');
        new_win.opener = window;
        new_win.focus();
        frm.body.value=frm.txt.value;
        frm.action="/pdfWriter";
        frm.target='new_win';
        frm.submit();
    }
    function docxwrite(frm)
    {if(_iseditmode)
            document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();
        var frm=document.frmtext;
        new_win = window.open('','new_win', 'menubar=no,scrollbars=yes,width=600,height=340,status=no,resizable=yes,top=200,left=200,dependent=yes,alwaysRaised=yes');
        new_win.opener = window;
        new_win.focus();
        frm.body.value=frm.txt.value;
        frm.action="/docxWriter";
        
        frm.submit();
    }
    function showconv()
    {
        document.getElementById("saveinprogress").style.display="block";
        document.getElementById("sip").src="/images/saveinprogress.gif";
    }
    function switchlang(lang) {
        var url=location.href;
        if (url.indexOf("cmdlang")>-1)
            url=url.substring(0,url.indexOf("cmdlang"));
        url+="&cmdlang="+lang;
        location.href=url;
    }
    function gohtml(){
        if(_iseditmode)
            document.frmtext.txt.value=window.frames["page_win"].oCKeditor.getData();
        var frm=document.frmtext;
        var jsrc=getsrc();
        if(jsrc.length>0)
            frm.txt.value+="<script language=javascript>"+jsrc+"</script>";
        frm.body.value=frm.txt.value;
        frm.iswebpage.value="1";
        popupNote();
        frm.action="/s_viewpagehtml.jsp";
        frm.target='comp_win';
        window.open("", "comp_win", "menubar=yes,scrollbars=yes,width=736,height=700,status=no,resizable=yes,dependent=yes,alwaysRaised=yes");
        frm.submit();
        self.close();
    }
    function popupNote(){
        alert("Right click the new popup page and "Save as" a HTML file.");
    }
    function setfrmheight() {
		
        $("#page_win").height($("body").height() - ($("#header").height()));
    }
    </script>
    <script type="text/javascript" src="/js/ssfunctions.js?v=201711.05"></script>
    <style>
        html,body{
            height:100%;
            overflow: hidden;
        }
        body{
            min-width:100%;
            max-width:100%;
            width:100%;
        }
    </style>
</head>
<body scroll="no" onload="puttxt();setfrmheight();" onresize="setfrmheight();">
    <!--<div style="display:none;width:100%;height:100%;top:0;left:0;position:absolute;background:#FFFFFF;z-Index:200;opacity:0.8;filter:alpha(opacity=80);text-align:center" id="saveinprogress"><table height="100%" width="100%" cellspacing="0" cellpadding="0"><tr><td valign="middle" align="center"><img src='/images/blank.gif' id="sip"><br><strong style='font-size:16pt;color:#697F39'>PDF Creation in Progress</strong><br><strong style='font-size:12pt;color:#697F39'>Please Wait</strong></td></tr></table></div>-->
    <div style="display:none;width:100%;height:100%;top:0;left:0;position:absolute;background:#FFFFFF;z-Index:200;opacity:0.8;filter:alpha(opacity=80);text-align:center" id="saveinprogress"><table width="100%" height="100%" cellspacing="0" cellpadding="0"><tbody><tr><td valign="middle" align="center"><img src="/images/blank.gif" id="sip" alt="Save In Progress"><br><div style="font-size:16pt;font-weight:bold;color:#697F39" id="smsg">PDF Creation in Progress</div><br><strong style="font-size:12pt;color:#697F39">Please Wait</strong></td></tr></tbody></table></div>
    <div id="header">
        
        
        <table width="100%" cellspacing="0" cellpadding="0" border="0">
            <tbody><tr>
                <th class="Title">Web Page View Actions</th>
            </tr>
        </tbody></table>
        
        <form name="frmtext" target="page_win" action="s_savetextfile.jsp" method="POST">
        <input name="ss_formtoken" id="ss_formtoken" value="0A0133DEE42C7A11D0AA8C8988695CEDAA905422B38099B3C0C9B463CEDC7663" type="hidden">
        <input value="1127956" name="objectid" type="hidden">
        <input value="" name="folderid" type="hidden">
        <input value="0" name="peopleid" type="hidden">
        <input value="0" name="varcontactid" type="hidden">
        <input value="2" name="format" type="hidden">
        <input value="" name="pswd" type="hidden">
        <input value="1" name="peopletypeid" type="hidden">
        <input value="1" name="iswebpage" type="hidden">
        <input value="" name="body" type="hidden">
        <input value="" name="subject" type="hidden">
        <input value="" name="cc" type="hidden">
        <input value="0" name="touser" type="hidden">
        <input value="0" name="maxp" type="hidden">
        <input value="Examinee_Notice_1127956" name="pdfname" type="hidden">
        <input value="Examinee_Notice_1127956" name="filename" type="hidden">
        <input value="24" name="entity" type="hidden">
        <input value="102946" name="appid" type="hidden">
        
        <table width="100%" cellspacing="0" cellpadding="0" border="0">
            <tbody><tr>
                <td class="Title">
                    <table cellspacing="0" cellpadding="0" border="0">
                        <tbody><tr>
                            <td colspan="3">
                                
                                <input name="cmdedit" id="cmdedit" class="ButtonSm" value="Edit" onclick="editdoc(this)" type="button">
                                
                                <input name="cmdemailpdf" id="cmdemailpdf" style="display: inline;" class="ButtonSm" value="Email as PDF" onclick="emailpdf()" type="button">
                                
                                <input name="cmdpdf" id="cmdpdf" style="display: inline;" class="ButtonSm" value="Export as PDF" onclick="pdfwrite();" type="button">
                                
                            </td>
                        </tr>
                    </tbody></table>
                </td>
            </tr>
        </tbody></table>
        
        
        <table id="functable" name="functable" width="100%" cellspacing="0" cellpadding="0" border="0">
            <tbody><tr>
                <td class="Title">
                    <div style="float:right;padding:4px 4px 0 0">
                        
                        Folder Name: <select name="mfolderid" class="AppNav" style="max-width:300px"><option value=""> --Select a folder-- </option><option value="1267619">Active Drafts</option>
<option value="1267614">Active Medical File</option>
<option value="1269758">Adjuster Service Requests (ARF - Portal)</option>
<option value="1267610" selected="">Adjuster, Assessor, Examinee And Legal Rep Communications</option>
<option value="1267616">Archived Medical File</option>
<option value="1274156">Client Invoices</option>
<option value="1269519">Correspondence - Notice to Assessor forms &amp; Assessment Plans</option>
<option value="1267612">Correspondence - Other</option>
<option value="1267620">Final Reports</option>
<option value="1267615">IME Guidelines Kits</option>
<option value="1267621">Informed Consent</option>
<option value="1267623">Provider Invoices</option>
<option value="1269372">Invoices and Consents</option>
<option value="1269448">Medical Briefs and Insurer Examination Reports</option>
<option value="1273039">Previous Drafts</option>
<option value="1267609">Production and Court Prep</option>
<option value="1273836">Referral Mandate</option>
</select>
                        
                    </div>
                    <input name="cmdsavepdf" class="Button" value="Save To Server as PDF" onclick="saveserver(1)" type="button">
                </td>
            </tr>
        </tbody></table>
        
        <textarea cols="0" rows="0" name="txt" style="display:none">
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
   &lt;head&gt;
      &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
      &lt;title&gt;Claimant Notice&lt;/title&gt;
      &lt;style type="text/css"&gt;		
         Table td 
         {
         padding: 3px;  
         vertical-align: top;
         }
         body
         {
         font-size:10pt;font-family:arial;				
         }
      &lt;/style&gt;
      &lt;script language="JavaScript" src="/jquery/jquery.js?v=201711.05"&gt;&lt;/script&gt;
      &lt;style&gt;&lt;/style&gt;
      &lt;script type="text/javascript"&gt;
         $(document).ready(function(){                      
         alert('aaa');   
        $('#cmdedit').hide();   
         	}
         });
      &lt;/script&gt;
   &lt;/head&gt;
   &lt;body&gt;
      &lt;table width="700px" border="0" align="center" cellpadding="0" cellspacing="0"&gt;
         &lt;tbody&gt;
            &lt;tr&gt;
               &lt;td&gt;                    
                  Test Test						
               &lt;/td&gt;
            &lt;/tr&gt;
         &lt;/tbody&gt;
      &lt;/table&gt;
   &lt;/body&gt;
&lt;/html&gt;</textarea>
    </form>
    </div>
      <div class="iframe_ipad">
    <iframe src="/s_blank.html" id="page_win" name="page_win" style="height: 71px;" width="100%" frameborder="0"></iframe>
      </div>

</body></html>

您正在尝试从<iframe>内执行的JavaScript代码中使用ID cmdedit隐藏元素。但是该元素不在 <iframe>中,因此jQuery找不到它。

您需要告诉jQuery在哪里寻找元素。您可以通过将第二个参数传递给jQuery选择器来做到这一点。从jQuery API文档页面:

jQuery(选择器[,上下文](

选择器
类型:选择器
一个包含选择器表达式的字符串

上下文
类型:元素或jQuery
用作上下文 -

因此,您只需要传递顶部窗口文档对象才能选择以隐藏它的元素。

    $(function(){
        $("#cmdedit", window.top.document).hide()
    });

或者您可以使用主窗口的jQuery

window.top.$("#cmdedit").hide();

或者您可以使用普通JavaScript

window.top.document.getElementById('cmdedit').style.display = 'none';

尝试此

$('#cmdedit').css('display','none');
$('#cmdedit').css('height',0);
$('#cmdedit').css('width',0);
$('#cmdedit').css('visibility','hidden');
$('#cmdedit').css('position','fixed');

固定的位置必须与隐藏的可见性结合在一起,以免从文档中占用空间。

虽然不是最好的做法,但是获得结果的第二种方法。

尝试:

<script>
        $(window).ready(function(){
            $('#cmdedit').hide();
        });
    </script>

希望这有所帮助。

最新更新