如何激活从 iframe 获取的 javascript 标签?
我有一个 Javascript 富文本编辑器,我希望能够在 Javascript 标记中输入嵌入的小部件。 即:
<script src="http://www.mydomain.com/script.aspx?id=123" type="text/javascript"></script>
仍然使用 JS,我将 html 内容从 iframe 移动到页面中的 DIV 中:
<script>
function copyRtfToDiv()
{
myiframe = document.getElementById('myiframe');
postDiv = document.getElementById('blogPostDiv');
content = myiframe.contentWindow.document.body.innerHTML;
postDiv.innerHTML = content;
}
</script>
当内容复制到 DIV 中时,不会调用脚本。 有没有办法让这个脚本运行?
I have a Rich Text Editor in Javascript in which I want to be able to enter an embedded widget in a Javascript tag. I.e:
<script src="http://www.mydomain.com/script.aspx?id=123" type="text/javascript"></script>
Still using JS I move the html-content from the iframe into a DIV in the page:
<script>
function copyRtfToDiv()
{
myiframe = document.getElementById('myiframe');
postDiv = document.getElementById('blogPostDiv');
content = myiframe.contentWindow.document.body.innerHTML;
postDiv.innerHTML = content;
}
</script>
When the content is copied into the DIV the script is not invoked. Is there a way to make this script run?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您似乎将 JavaScript 代码复制到 DIV 标记中。 这应该不起作用,因为它只会将其视为常规文本。 为了说明这一点,请比较这两个代码块。 第一个是 DIV:
它会在页面上显示,如下所示:
alert('hello!');
第二个代码块是一个脚本:
它将打开一个带有文本“hello!”的消息框,并等待用户单击“确定”。 但除此之外,不会在页面中显示任何内容。
您的目标是第二个选项 - 实际上运行驻留在标记之间的 JavaScript 代码的选项。
我建议将要调用的脚本包装在函数中,并按名称调用该函数。 假设您在 IFRAME 中有一个 HTML 文档,其正文如下所示:
然后,您可以在 IFRAME 的父文档(包含
标记的文档)中使用以下内容父级中的代码将其导入到父级的 DOM 中:
我不知道为什么你会想要做这样的事情 - 这基本上是重新设置 JavaScript 代码的父级以使其存在于文档的 DOM 中; 有更好的方法可以做到这一点,其中最重要的是使用可以简单地从外部调用的不同编辑器。 例如,tinyMCE 和 FCKEditor.
祝你好运!
First off, you seem to be copying JavaScript code into a DIV tags. That shouldn't really work, since it'll just treat it like regular text. To illustrate, compare these two blocks of code. The first, is a DIV:
And it'll look on the page, like this:
alert('hello!');
The second block of code, is a script:
Which will open a message box with the text "hello!", and await a user-click on "OK". But other than that, won't display anything in the page.
You're aiming for the 2nd option - one that actually runs the JavaScript code that resides between the tags.
I'd recommend wrapping the script you want to invoke in a function, and invoking that function by name. So let's say you have within the IFRAME an HTML document whose body looks something like this:
You could then, in the IFRAME's parent document (the one containing the
<iframe>
tag), to use the following code in the parent to import it into the parent's DOM:I have no clue why you would want to do something like this - which is basically re-parenting JavaScript code to live within you document's DOM; There are better ways to do this, not least of which is using a different editor that can be simply called externally. For example, tinyMCE and FCKEditor.
Good luck!