如何在没有类或id的iFrame中获取链接

How to get link in iFrame without class or id

本文关键字:iFrame 获取 链接 id      更新时间:2023-09-26

我想使用jquery在iframe中找到一个链接。他的脚本示例:

<body>
    <iframe src='content.html' framborder='0'>
        <html>
            <body>
                <div class="afk">
                    <a href='index.html' target='_blank'>
                        <p>Text Here</p>
                    </a>
                </div>
            </body>
        </html>
    </iframe>
    <iframe src='content.html' framborder='0'>
        <html>
            <body>
                <div class="afk">
                    <a href='index-2.html' target='_blank'>
                        <p>Text Here</p>
                    </a>
                </div>
            </body>
        </html>
    </iframe>
</body>

如何获取iframe中链接的"href"值?

您可以使用

    //select frames
    var iframes = jQuery('iframe');
    $.each(iframes, function(i, iframe){
//this gives access to the window object of iframe
     childWindow = iframe.contentWindow;
      //now fire your selector query here
     console.log(childWindow.document.querySelector("div a").href); 
//or console.log(childWindow document.querySelector("div a").getAttribute("href"));
    })

首先,您必须等待加载iframe,如果iframe-src具有权限,您可以像另一个页面dom一样访问iframe的dom。

$('#myiframeid').load(function(){
  $(this).contents().find('a').each(function(){
    console.log($(this).attr('href'));
  });
});