在document.write里面运行函数window.wn里面的document.write

时间:2015-06-17 09:52:58

标签: javascript function alert window.open document.write

function capture(){
  var screenshot = window.open("", "_blank", "menubar=2,titlebar=0,toolbar=0,width=" + 680 + ",height=" + 550);
  screenshot.document.write("<center/><img id='jpeg' src='"+img+"'><br/>");
  screenshot.document.write("<a download='vfr_capture.jpeg' href='"+img+"'>Download</a>");
  screenshot.document.write("<button id='myLink' onclick='popOut()'>Test</button>");
}
function popOut(){
  alert("Clicked");
}

按钮myLink出现在window.open之后,如果我点击它就不会发生。如何显示警报(“点击”)?在document.write中是否禁用了onclick函数?

PS:我试过将函数popOut()放在函数capture()之上,但它仍然不起作用。请帮忙。

2 个答案:

答案 0 :(得分:1)

弹出窗口中popOut中的onclick不是当前窗口中的popOut。两个窗口环境是分开的。

您可以将其添加到其他窗口,方法是将其添加到capture的末尾:

screenshot.popOut = popOut;

Live Example: (因为Stack Snippets不允许window.open

document.querySelector('input').onclick = capture;
function capture(){
  var screenshot = window.open("", "_blank", "menubar=2,titlebar=0,toolbar=0,width=" + 680 + ",height=" + 550);
  /* Commented out since I don't have your `img` variable
  screenshot.document.write("<center/><img id='jpeg' src='"+img+"'><br/>");
  screenshot.document.write("<a download='vfr_capture.jpeg' href='"+img+"'>Download</a>");
  */
  screenshot.document.write("<button id='myLink' onclick='popOut()'>Test</button>");
  screenshot.popOut = popOut;
}
function popOut(){
  alert("Clicked");
}

HTML:

<input type="button" value="Click me">

答案 1 :(得分:0)

两个功能都在不同的范围

function capture() {
    var screenshot = window.open("", "_blank", "menubar=2,titlebar=0,toolbar=0,width=" + 680 + ",height=" + 550);
    screenshot.document.write("<center/><img id='jpeg' src='" + img + "'><br/>");
    screenshot.document.write("<a download='vfr_capture.jpeg' href='" + img + "'>Download</a>");
    screenshot.document.write("<button id='myLink'>Test</button>");

    screenshot.document.getElementById('myLink').onclick = popOut
}

演示:Fiddle