代码之家  ›  专栏  ›  技术社区  ›  Anthony

使用jquery从父窗口遍历/操作新窗口

  •  4
  • Anthony  · 技术社区  · 16 年前

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

    目标是设置新窗口的 img src 作为用户单击以打开新窗口的图像。但是在上面的场景中,我只是想打开新窗口来获取它已经设置的src。我有 imgwin.html 已使用默认值写入 所以它应该提醒这个url。相反,我只是 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的指针。

    注:

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

    2 回复  |  直到 16 年前
        1
  •  2
  •   jitter    16 年前

    又快又脏

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

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

        2
  •  2
  •   Community Mohan Dere    6 年前

    $("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);