我尝试执行一个javascript函数,该函数会更改每个iframe的源代码。如果iframe不在任何其他标签内,则可以使用。
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<button onclick="myFunction()">Search</button>
<iframe src="https://www.espn.com" frameborder="1" width="500" height="320"></iframe>
<iframe src="https://www.nbc.com" frameborder="1" width="500" height="320"></iframe>
<iframe src="https://www.cnn.com" frameborder="1" width="500" height="320"></iframe>
<script type = "text/javascript">
function myFunction(){
alert("Hello!");
var frames = window.frames;
for (var i = 0; i < frames.length; i++){
frames[i].location = "http://www.w3schools.com";
}
}
</script>
</body>
</html>
如果我将iframe放在div标签中,javascript因某些原因无法访问它们。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<form align = "center">
<br>
<button onclick="myFunction()">Search</button>
<br>
</form>
<div class="col-xs-8 col-lg-6">
<h3 id = "ESPN">ESPN</h3>
<iframe src="https://www.espn.com" frameborder="1" width="500" height="320"></iframe>
<br>
</div>
<div class="col-xs-8 col-lg-6">
<h3 id = "NBC">NBC</h3>
<iframe src="https://www.nbc.com" frameborder="1" width="500" height="320"></iframe>
<br>
</div>
<div class="col-xs-8 col-lg-6">
<h3 id = "CNN">CNN</h3>
<iframe src="https://www.cnn.com" frameborder="1" width="500" height="320"></iframe>
<br>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type = "text/javascript">
function myFunction(){
alert("Hello!");
var frames = window.frames;
for (var i = 0; i < frames.length; i++){
frames[i].location = "http://www.w3schools.com";
}
}
</script>
</body>
</html>
为了让我的函数能够读取iframe,我还需要做些什么吗?
答案 0 :(得分:2)
function myFunction(){
alert("Hello!");
var frames = window.getElementsByTagName("iframe"); // You only want iframes
for (var i = 0; i < frames.length; i++){
frames[i].src = "http://www.w3schools.com";
}
}
答案 1 :(得分:1)
var frames = window.querySelectorAll("iframe");
获取所有iframe。
我不确定,但您也可以将您的线路更改为
frames[i].src = "http://www.w3schools.com";
答案 2 :(得分:0)
试试这个
frames[i].src= "http://www.w3schools.com";
而不是那个
frames[i].location = "http://www.w3schools.com";
答案 3 :(得分:0)
您需要使用以下内容替换您的javascript:
function myFunction() {
alert("Hello!");
var frames = document.getElementsByTagName("iframe");
for (var i = 0; i < frames.length; i++) {
frames[i].src = "http://www.w3schools.com";
}
}