简体   繁体   English

使用JavaScript更改HTML iframe的本地src

[英]Using JavaScript to change local src of an HTML iframe

Lets say you have a main .html: 假设您有一个主要的.html:

<!DOCTYPE html>
<html>
<head>
    <title>Page One</title>
    <script type="text/javascript" src="javaS.js"></script>
    <link rel="stylesheet" type="text/css" href="CSS.css">
</head>
<body id="main">
<h3>Test switching html content inside iframe</h3>
<p>iframe:</p>
<iframe src="" id="iframe1"></iframe>
</body>
</html>

And a secondary .html: 和辅助.html:

<!DOCTYPE html>
<html>
<head>
    <title>Page two</title>
    <link rel="stylesheet" type="text/css" href="CSS.css">
</head>
<body id="test">
<h3>Test subject</h3>
<p>subjugate text</p>
</body>
</html>

How would you display the local second .html inside the iframe element of the first .html, using only JavaScript? 如何仅使用JavaScript在第一个.html的iframe元素内显示本地第二个.html?

I have tried using these snippets: 我尝试使用以下代码段:

window.onload = function() {window.frames['iframe1'].location.replace("Secondary.html");}

.

var iframe = document.getElementById('iframe1');
iframe.src = "second.html"; 

...But these haven't worked. ...但是这些都没有用。 I'm new at this so the answer might be fairly obvious, but any guidance would be very much appreciated! 我是新来的,所以答案可能很明显,但是任何指导都将不胜感激!

I use this and it works well: 我用它,它很好用:

window.onload = function()
{
    document.getElementById('iframe1').src = "Secondary.html";
}
document.getElementsByTagName("iframe")[0].setAttribute("src", "http://your-url.com");

Your second snippet is perfect. 您的第二个片段是完美的。 You just have to make sure that it runs when iframe DOM element exists - in window.onload . 您只需要确保它在iframe DOM元素存在时在window.onload

I just combined the two exampples you had tried to make one working example, see here: https://jsfiddle.net/4p18mxg9/9/ 我只是结合了您试图创建一个工作示例的两个示例,请参见此处: https ://jsfiddle.net/4p18mxg9/9/

var iframe = document.getElementById('iframe1');
window.onload = function() {
    iframe.src = "second.html";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM