javascript 使用 window.frames 属性与 iframe ID 获取 iframe
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21656285/
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
Get iframe with window.frames property vs. iframe ID
提问by Mori
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:
但是,如果您直接使用 iframe 访问 iframe ID
,则它可以正常工作:
<!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?
我怎样才能window.frames
让第一个代码正常运行?
采纳答案by User3269771
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 recommend accessing it by id.
这对您不起作用,因为它将返回框架内的 window 对象而不是 iframe 元素。如果您想使用可以使用的 name 属性,document.getElementsByName("myFrame")[0]
但我建议您通过 id 访问它。
回答by user3289004
I think you have to do a for loop to find all the frames and then access them by their index.
我认为你必须做一个 for 循环来找到所有的帧,然后通过它们的索引访问它们。
for(var i=0; i < frames.length; i++) {
console.log(frames[i]);
}
回答by WISeAgent
It should work the same for getElementsByName, mind you that it returns an array of element, not an element.
它应该对 getElementsByName 起作用,请注意它返回一个元素数组,而不是一个元素。
Both statements should have the same effect for frame with name of "myFrame", and id of "myFrame":
对于名称为“myFrame”且 id 为“myFrame”的框架,这两个语句应该具有相同的效果:
document.getElementsByName("myFrame")[0].style.background = "green";
document.getElementById("myFrame").style.background = "green";