如何使用javascript从iframe提取链接

如何使用javascript从iframe提取链接,javascript,jquery,Javascript,Jquery,例如: iframe.html <a href="http://www.google.com">Google</a> bla bla bla <a href="http://www.yahoo.com">Yahoo</a> 呜呜呜呜 index.html <script> ... </script> There are the links from "iframe.html" http://www.google.com

例如:

iframe.html

<a href="http://www.google.com">Google</a>
bla bla bla
<a href="http://www.yahoo.com">Yahoo</a>

呜呜呜呜
index.html

<script>
...
</script>
There are the links from "iframe.html"
http://www.google.com
http://www.yahoo.com

...
有来自“iframe.html”的链接
http://www.google.com
http://www.yahoo.com

假设您的iframe与您的网站位于同一个域中,并且id为“my_iframe”,并且您有一个id为“results”的div,这应该适用于您:

$("#my_iframe").contents().find('a').each({
    $('#results').append($(this).attr('href') + '<br />');
});
$(“#我的iframe”).contents().find('a')。每个({
$(“#结果”).append($(this.attr('href')+”
); });

花点时间阅读JQuery的函数

如果域、协议和端口匹配,只需使用

var links = $('iframe:first').contents()[0].links;

…或者没有jQuery

var iframe = document.getElementsByTagName('iframe')[0],
    doc = iframe.contentDocument || iframe.contentWindow.document; 

var links = doc.links;


这利用了属性。

index.html和iframe.html是否在同一个域中?
iframe.html
是否与
index.html
具有相同的域、协议和端口?请参见此答案@阿德尔:那就是检测字符串中的URL。OP需要DOM中的链接。这很酷,但他仍然需要迭代该数组来显示它们,很可能是使用
$。each()
因此,只需直接从
contents()
选择器迭代锚点,就不会节省太多精力,对吗?@AlienWebGuy它返回的不仅仅是
a
元素,而且只有
a
元素具有
href
属性。这种添加到
#results
的方法有点麻烦。为什么不
append()
?很好的调用,我只使用它来附加特定的节点,但是添加字符串也很有意义。谢谢男人:)