问题
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