传递JavaScript函数以在新的窗口对象中运行 [英] Passing a JavaScript function to run in a new window object
问题描述
假设我有一个HTML字符串,可以使用以下方法将其传递给新窗口/浏览器:
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);
如您所见,一旦将HTML字符串传递到新窗口并进行渲染,就会有一个按钮(#copy-all
)以及所有内容.
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.
问题是-如何将JavaScript函数(无论是否使用jQuery)附加到按钮上,以使我能够操纵放置在div(#contents-container
)元素内的DOM?我尝试将函数文字作为htmlStr
变量的一部分,但它似乎不是一个可行的选择.
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.
推荐答案
使用jQuery,我会这样:
With jQuery I would do it like this:
$('#copy-all', doc).on('click', function() {
$('#contents-container', doc).html('test');
});
这是正在工作的JSFiddle: http://jsfiddle.net/qd8dybg0/2/(不要忘记禁用弹出窗口阻止程序)
Here is a working JSFiddle: http://jsfiddle.net/qd8dybg0/2/ (don't forget to disable your popup blocker)
这篇关于传递JavaScript函数以在新的窗口对象中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!