我通过点击按钮调用以下功能打开新窗口/选项卡并显示警告并更新文本:
function nWin(p) {
var setStyle = "<style rel='stylesheet'>\
.vTop {\
vertical-align: top;\
}\
<\/style>";
var setScript = "<script>alert('test');<\/script>";
setScript += "<script src='http://code.jquery.com/jquery-1.11.0.min.js'><\/script>";
setScript += "<script>$(function () { $('#sText').html('UPDATED TEST'); });<\/script>";
var w = window.open();
var createBody = $(w.document.body);
var createHead = $(w.document.head);
createBody.html("");
createBody.html(p);
createBody.append("<span id='sText'>THIS IS A TEST</span>");
createHead.html(setStyle);
createHead.append(setScript);
}
当我点击按钮时,从页面显示警报我单击按钮而不是在创建的窗口/选项卡上,sText
文本也不会更改。
以下是HTML来源:
如何解决它以使其正常工作,在新窗口/选项卡中显示警报,同时更新范围文本。
答案 0 :(得分:1)
您需要更改将内容添加到新窗口的方法。以下作品;
function nWin(p) {
var setStyle = "<style rel='stylesheet'>\
.vTop {\
vertical-align: top;\
}\
<\/style>";
var setScript = "<script>alert('test');<\/script>";
setScript += "<script src='http://code.jquery.com/jquery-1.11.0.min.js'><\/script>";
setScript += "<script>(function () { $('#sText').html('UPDATED TEST'); })();<\/script>";
var w = window.open();
w.document.write('<head>');
w.document.write(setStyle);
w.document.write('</head><body>');
w.document.write("<span id='sText'>THIS IS A TEST</span>");
w.document.write(setScript);
w.document.write('</body>');
}
请参阅this Fiddle
答案 1 :(得分:0)
试试这个:
function doSomeThing(){
alert('test');
setTimeout('document.getElementById(\'sText\').innerHTML=\"UPDATED TEST\"',500);
document.getElementById('sText').innerHTML="UPDATED TEST";
}
function nWin(p) {
var setStyle = "<style rel='stylesheet'>\
.vTop {\
vertical-align: top;\
}\
<\/style>";
var w = window.open();
var createBody = $(w.document.body);
var createHead = $(w.document.head);
createHead.html(setStyle);
var script = w.document.createElement('script');
script.appendChild(document.createTextNode('('+ doSomeThing+')();'));
(w.document.body || w.document.head || w.document.documentElement).appendChild(script);
createBody.html("");
createBody.html(p);
createBody.append("<span id='sText'>THIS IS A TEST</span>");
}