Javascript 使用Javascript动态设置frame src

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5842040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:09:36  来源:igfitidea点击:

Dynamically set frame src using Javascript

javascripthtmlcss

提问by testndtv

I have a HTML element

我有一个 HTML 元素

<frame src="#" title="Content Frame" name="content" id="content" />

I want to set it's "src" dynamically using Javascript on page load. How can I do that ?

我想在页面加载时使用 Javascript 动态设置它的“src”。我怎样才能做到这一点 ?

I am trying something like;

我正在尝试类似的东西;

document.getElementById('content2').contentWindow.location = 'xyz_frame.html';

But for some reason it is not working..Again it is a element and not

但由于某种原因它不起作用..再次它是一个元素而不是

A Rough code;

一个粗略的代码;

<html>
<head>
<script language="javascript"> 
function LoadPage(){ 
document.getElementById('content2').src = 'ipad_lrd_frame.html';
}
</script> 
</head>
<body onload="LoadPage()">
<frame id="content2"></frame>
</body>

</html>

回答by Alex K.

This should work;

这应该有效;

document.getElementById('content2').src = "url";

(Also you have mismatched IDs for the frame and getElementByIdcall)

(此外,您的框架和getElementById呼叫的ID 不匹配)

For a FRAME, you need a FRAMESETwhich precludes the use of a BODY, so;

对于 a FRAME,您需要 aFRAMESET排除使用 a BODY,所以;

<frameset rows="50%,*" onload="LoadPage();">    
   <frame id="content2"></frame>
   .....

Update:

更新:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<script type="text/javascript">
function LoadPage(){
    document.getElementById('content1').src = "http://www.google.com";
    document.getElementById('content2').src = "http://www.bing.com";
}
</script>
<title></title>
</head>
<frameset rows="50%,*" onload="LoadPage();">    
    <frame src="#" id="content1">    
    <frame src="#" id="content2">                
</frameset>
</html>

回答by lpd

I would think fetching frames by name would be more suitable:

我认为按名称获取帧会更合适:

document.getElementsByName('content2')[0].src = 'ipad_lrd_frame.html';

Tested it successfully. Ensure your page uses a frameset doctypeand you do notinclude bodytags (use framesettags instead). Also note your script type should be text/javascript, rather than language "javascript".

测试成功。确保您的页面使用框架集doctype并且包含body标签(改用frameset标签)。另请注意,您的脚本类型应该是text/javascript,而不是语言“javascript”。