使用jquery .clone启动具有正常运行的侦听器的新窗口

时间:2014-05-29 14:55:36

标签: javascript jquery

我正在尝试在其现有状态下制作页面的副本,在新窗口中启动它,并使侦听器保持正常运行。最终,我只想克隆一部分页面,但是现在我只是想让它与整个页面一起工作。

我有以下功能:

function clonePage() {
    var printWindow = window.open(''),
        html = $('html').clone(true, true);

    printWindow.document.write("<!DOCTYPE html><html><head></head><body></body></html>");

    $(printWindow.document).find('html').replaceWith(html);
}

当我运行它时会发生什么,如果我在新窗口中点击带有监听器的内容,它会影响旧窗口中的页面。

我创建了一个codepen来举例说明这个问题。如果单击“克隆我”按钮,然后单击新窗口上的“警报”按钮,则会在父窗口中显示警报。

http://codepen.io/MerceanCoconut/pen/BKEJi

1 个答案:

答案 0 :(得分:0)

修改

尝试(在console,此页面)

var _jq = "http://code.jquery.com/jquery-1.11.1.min.js";
var _div = $("#answer-23937038").get(0).outerHTML; // target `div`
// if `event` `listeners` and `plugin` pieces are in file, 
// utilize same approach as jquery, i.e.g,
// `<script src=" + _eventListenersFileSrc + ">`,
// else, compose script(s) as `string`(s), 
// and escape quotes, .e.g, `\"`
var _script = "<script>$(function() { $(\"#answer-23937038\").on(\"click\"," 
              + "function(e) { alert($(e.target).text()) })})</script>";
$("<a>", { 
  "href" : "data:text/html;charset=utf-8,<!DOCTYPE html><html><head><script src=" 
           + _jq + "></script>"
           + _script
           + "</head><body>" 
           + _div 
           + "</body></html>",
  "target" : "_blank", 
  "html" : "view data in new tab"})
.appendTo($("body"));