javascript - 从 iframe 中的元素获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7944937/
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
javascript - get data from an element within an iframe
提问by laarsk
I've got this <iFrame>
[name="data"] with a page displaying a <span>
, with id="weergave_percentage".
I want to get the numbers from that span into a javascript function.
I currently made this, but it returns: null
我有这个<iFrame>
[name="data"] 页面显示<span>
id="weergave_percentage"。我想从那个跨度中获取数字到一个 javascript 函数中。我目前做了这个,但它返回:null
var percentage = window.frames['data'].document.getElementById('weergave_percentage');
alert(percentage);
What am I doing wrong and how can I do what I want?
我做错了什么,我该如何做我想做的事?
Note: the span containing the data, only contains numbers (float), and no other HTML formatting of any kind. Also, I've put the piece of javascript after the code for the iFrame, to make sure the iFrame is loaded when I try to get the data from the iFrame. Also, the iFrame's src is on the same domain as the main page.
注意:包含数据的跨度仅包含数字(浮点数),不包含任何其他 HTML 格式。此外,我已将这段 javascript 放在 iFrame 的代码之后,以确保在我尝试从 iFrame 获取数据时加载了 iFrame。此外,iFrame 的 src 与主页在同一个域中。
回答by
If iframe src links to other domain than the one your pages is displayed from - then you can't get that data (browsers prevernt cross-site scripting).
如果 iframe src 链接到其他域而不是显示您的页面的域 - 那么您将无法获取该数据(浏览器防止跨站点脚本)。
Other than that - this could should work:
除此之外 - 这应该可以工作:
$('iframe').contents().find('#weergave_percentage').html();