admin管理员组文章数量:1401610
I wonder why the following doesn't work:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Iframe</title>
<style>
</style>
</head>
<body>
<iframe name="myFrame"></iframe>
<script>
window.frames["myFrame"].style.background = "green";
</script>
</body>
</html>
However, if you access the iframe directly using its ID
, it works with no problem:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Iframe</title>
<style>
</style>
</head>
<body>
<iframe id="myFrame"></iframe>
<script>
document.getElementById("myFrame").style.background = "green";
</script>
</body>
</html>
How can I use window.frames
to get the first code to run properly?
I wonder why the following doesn't work:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Iframe</title>
<style>
</style>
</head>
<body>
<iframe name="myFrame"></iframe>
<script>
window.frames["myFrame"].style.background = "green";
</script>
</body>
</html>
However, if you access the iframe directly using its ID
, it works with no problem:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Iframe</title>
<style>
</style>
</head>
<body>
<iframe id="myFrame"></iframe>
<script>
document.getElementById("myFrame").style.background = "green";
</script>
</body>
</html>
How can I use window.frames
to get the first code to run properly?
3 Answers
Reset to default 2I think you have to do a for loop to find all the frames and then access them by their index.
for(var i=0; i < frames.length; i++) {
console.log(frames[i]);
}
This doesn't work for you, because it will return the window object inside of the frame and not the iframe element. If you want to use the name attribute you can use document.getElementsByName("myFrame")[0]
but I'd remend accessing it by id.
It should work the same for getElementsByName, mind you that it returns an array of element, not an element.
Both statements should have the same effect for frame with name of "myFrame", and id of "myFrame":
document.getElementsByName("myFrame")[0].style.background = "green";
document.getElementById("myFrame").style.background = "green";
本文标签: javascriptGet iframe with windowframes property vs iframe IDStack Overflow
版权声明:本文标题:javascript - Get iframe with window.frames property vs. iframe ID - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744320957a2600491.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论