我有一个源 HTML 页面,通过单击通用按钮打开一个虚拟(未绑定(bind)到文件)弹出窗口,然后在其 innerHTML
中推送一些 Html 和 Javascript 代码.
这是源页面的简短摘录,我在其中定义了弹出窗口的 Html+Javascript 内容并将其打开:
<script language="javascript">
<!--
function fxOpenWindow()
{
// Init objects
var retVal = ''; // contains the Html+Javascript to push in the pop-up innerHTML
var popup = ''; // pop-up to open, not generated by loading a file but only by pushing the "retVal" code inside its innerHTML
// constructing the HTML to push
// defining a function() to show a simple alert : "1"
retVal = retVal + '<script>';
retVal = retVal + ' function fxMessage() { alert(1); }';
retVal = retVal + '</script>';
// defining the html object with which execute the above function
retVal = retVal + '<button onClick="fxMessage();">CLICK ME</button><br>';
// opening the virtual POPUP
popup = window.open('','title');
popup.document.body.innerHTML = retVal;
popup.focus();
}
-->
</script>
<button onClick="fxOpenWindow();">OPEN THE POP-UP WINDOW AND SHOW ITS CONTENT</button>
我的问题是我无法使 fxMessage()
函数工作,它根本不执行任何操作。
我也使用了eval()
方法,试图使字符串成为实时可执行代码:
// all these methods are a "NO-GO"
retVal = retVal + '<button onClick="fxMessage();">CLICK ME</button><br>';
retVal = retVal + '<button onClick="eval(fxMessage);">CLICK ME</button><br>';
retVal = retVal + '<button onClick="eval(fxMessage());">CLICK ME</button><br>';
// the "direct method" is the only one that works:
retVal = retVal + '<button onClick="alert(1);">CLICK ME</button><br>';
由于实际代码更复杂,我需要使用 function() 来简化我必须编写的一些递归调用,以便在弹出窗口本身中动态构建更多 html 对象,所以我真的很介意写onClick
事件中的所有代码;我不愿意做的另一件事是让弹出窗口加载存储在硬盘上的 html 文件,我在其中编写了所有 retVal 作为其 html,以便能够让 fxMessage()
函数正常工作:弹出窗口必须只是打开时仅驻留在内存中的虚拟页面。
我的问题是:有没有办法让 fxMessage()
在弹出窗口中提升为函数并使其正常工作?
最佳答案
如果您尝试插入一些 <script>
通过innerHTML
页面加载后,它将无法工作(我昨天已经解释过here)。
所以,移动fxMessage
对脚本的声明,例如:
<script>
fxOpenWindow(){
//Code here
}
fxMessage(){
//Code here
}
</script>
简单地称之为onclick="fxMessage()"
,不需要eval
在这里。
关于javascript - 如何使用 Javascript 从弹出窗口本身的源页面执行在 html 弹出窗口中实时创建/打印的 function() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58185172/