【问题标题】:Traversing/Manipulating new window from parent window with jquery使用jquery从父窗口遍历/操作新窗口
【发布时间】:2010-03-22 01:38:10
【问题描述】:

我发现一个问题已经有了可能的解决方案,但我在阅读之前已经尝试过建议的方法,它甚至说它不一致。所以我想我想知道为什么这不起作用:

$("img").click(function() {
    var imgwindow = window.open('imgwin.html','','width=460,height=345');
    alert(imgwindow.find("img").attr("src"));
});

目标是将新窗口的img 设置为与用户单击以打开新窗口的图像相同的src。但是在上面的场景中,我只是试图进入新窗口来获取它已经设置的 src。我已经为图像编写了imgwin.html,并使用了默认的src,因此它应该提醒该网址。相反,我只收到undefined

我还尝试了以下方法(后端应该相同),但结果相同:

$("img").click(function() {
    var imgwindow = window.open('imgwin.html','','width=460,height=345');
    alert($("img",imgwindow).attr("src"));
});

我什至尝试了将 imgwindow 变量包装在 $() 中的变体,以防 jquery 没有将变量作为 DOM 元素拾取。

我唯一能猜到的是,由于window.open() 是一种方法,jquery 不会将其视为 DOM 元素,即使基本 javascript 教程中的所有文档都将变量视为打开窗口的方法和指向窗口内部 DOM 的指针。

注意:

我通常更喜欢并向其他开发人员推荐使用 jquery-ui 对话框小部件,但在这种情况下,图像实际上是用户想要从主窗口弹出并打开的网络摄像头源,即使主窗口已关闭,因此,虽然我很欣赏从弹出窗口中的移动,但请避免建议涉及相同窗口小部件的替代方案。谢谢。

【问题讨论】:

    标签: javascript jquery dom browser window


    【解决方案1】:

    又快又脏

    var src = '';
    var imgwindow;
    $(function() {
      $("img").click(function() {
        imgwindow = window.open('urlto.html','','width=460,height=345');
        src = this.src;
        //delay needed as I couldn't manage to get ready/load events to work on the
        //imgwindow.document object
        //thus the snippet is dirtier then need with all those "global" variables
        setTimeout('$("img", imgwindow.document.body).attr("src", src)', 1000);
      });
    });
    

    注意:仅在 Opera 中测试。 imgwindow.document 可能不适用于所有浏览器。至少我记得 iframe 存在问题,其中需要 document/contentDocument 和其他“标识符”来获取新窗口/iframe 的“文档”。但只需在您需要支持的任何浏览器中进行测试

    【讨论】:

    • 我仍在努力消化您的回答,但我认为您的延迟问题实际上可能是我困惑的真正答案。我未定义的原因是因为警报发生时新窗口尚未加载。嗯,当然!如果是这种情况,我将测试这个理论并发布最终更新。
    【解决方案2】:

    为什么不这样做

    $("img").click(function(e) {
    var src = $(this).attr('src');
    window.open(src,'','width=460,height=345');
    });
    

    这将打开一个新窗口,其中包含您的图像! ;-)

    更新

    针对您的评论,需要做这样的事情:

    $("img").click(function(e) {
    //Load content in your page and hide it...
    $('#result').load('imgwin.html').hide();
    //find the image you want...
     alert($('#result').find("img").attr("src"));
    //remove it from your page..
    $('#result').remove();
    });
    

    更新 2

    好的,还是这个,我喜欢! ;-)

    试试这个:

    var reg = /src=\"(.+[\.jpg|\.jpeg|\.png|\.gif])\"/;  
    var imgwindow = $.ajax({type: "GET", url: "imgwin.html", async: false  }).responseText;
    var img = imgwindow.match(reg)[1];
    alert(img);
    

    【讨论】:

    • 我考虑过,但我需要将其他 HTML 嵌入到新窗口中,这样如果父窗口关闭,新窗口就有自己的控件。我很困惑为什么我找不到任何关于如何做到这一点的解决方案。不过感谢您的反馈。
    • 这是一个偷偷摸摸的解决方法。我必须承认它很聪明。但我尽可能避免隐藏,我认为抖动可能触及了我困惑的真正根源。 +1 创意。
    猜你喜欢
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多