Passing a JavaScript function to run in a new window object

梦想与她 提交于 2019-12-12 04:25:19

问题


Let's say I have a HTML string that gets passed to a new window/browser using the following method:

var htmlStr =
        "<div><button id='copy-all'>Copy all contents</button></div>" +
        "<div id='contents-container'>" +
        "    (lots of contents are placed here...) " +
        "</div>"
   , newWin = window.open("", "Test", "width=1000, height=800, scrollbars=1, resizable=1")
   , doc = newWin.document;

doc.write(htmlStr);

As you can see, there will be a button (#copy-all) along with all the contents once the HTML string is passed to the new window and rendered.

The question is - how can I attach a JavaScript function (with or without using jQuery) to the button that enables me to manipulate the DOM placed inside the div (#contents-container) element? I tried including a function literal as part of the htmlStr variable but it doesn't seem to be a viable option.


回答1:


With jQuery I would do it like this:

$('#copy-all', doc).on('click', function() {
    $('#contents-container', doc).html('test');
});

Here is a working JSFiddle: http://jsfiddle.net/qd8dybg0/2/ (don't forget to disable your popup blocker)




回答2:


A variant of Mario A's answer which uses jQuery that does not use jQuery:

doc.getElementById("copy-all").onclick = function(event) {
    doc.getElementById("contents-container").innerHTML = 'test';
};

And a demo JSFiddle (disable popup blocker to see demo): http://jsfiddle.net/kv2p8dwe/2/



来源:https://stackoverflow.com/questions/28033728/passing-a-javascript-function-to-run-in-a-new-window-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!