jQuery - 页面加载后插入的解析iframe

时间:2012-07-26 04:31:17

标签: javascript jquery iframe

我是jQuery的新手,遇到了一些麻烦。 A页面加载后插入iframe页面。我需要在iframe的内容中找到锚点链接,并将其href与网址进行比较。只是尝试纯JavaScript getElementById()不起作用,因为在加载后插入了iframe。我读到我应该使用jQuery的live()delegate()on(),但我不确定它们是如何工作的。此外,如果有一个纯粹的Javascript解决方案也很棒。

我需要解析的iframe是:

<iframe src="http://assets.tumblr.com/iframe.html?10&src=http%3A%2F%2Fstaff.tumblr.com%2F&amp;lang=en_US&amp;name=staff"
    scrolling="no" width="330" height="25" frameborder="0" 
    style="position:absolute; z-index:1337; top:0px; right:0px; 
           border:0px; background-color:transparent; overflow:hidden;" 
           id="tumblr_controls">
</iframe>

它附加到每个Tumblr博客(见Tumblr Staff Blog)。

我感兴趣的iframe内容部分如下:

<div style="position:absolute; top:3px; right:3px; white-space:nowrap; height:20px;">
    <form action="/follow" method="post" style="display:block; float:left;" onsubmit="_gaq.push(['_trackEvent', 'Iframe', 'Follow', 'staff');">
    <input type="hidden" name="form_key" value="8W0r1XnbOEtpTF0q8oe96BmGMJg"/>
    <input type="hidden" name="id" value="staff"/>
    <input type="image" src="http://assets.tumblr.com/images/iframe_follow_alpha.png 1018" style="width:58px; height:20px; border-width:0px; display:block; margin-left:3px; cursor:pointer;" alt="Follow"/>
    </form>
    <a target="_top" href="http://www.tumblr.com/dashboard">
    <img src="http://assets.tumblr.com/images/iframe_dashboard_alpha.png?1018" alt="Dashboard" style="height:20px; width:81px; border-width:0px; display:block; float:left; cursor:pointer;"/>
</a>

我需要比较此内容中的所有可能的锚链接,并将其href与网址进行比较。

3 个答案:

答案 0 :(得分:4)

function getHref() {

  var src = false,
      iframe = $('iframe#tumblr_controls');  // keep reference of iframe;
  // check that iframe loaded
  if( iframe.length) { 
     src = iframe.find('a[target=_top]').attr('href');
  }
}

现在,您可以致电getHref()获取iframe中的href链接并将其用于比较。

您还可以尝试以下内容:

$('iframe#tumblr_controls').load(function() {
   var href = $(this).find('a[target=_top]').attr('href');
});

如果您的内容中有多个a标记,请尝试:

function compareHrefs() {
  var iframe = $('iframe#tumblr_controls');  // keep reference of iframe;
  // check that iframe loaded
  if( iframe.length) { 
     // looping over each  tag
     iframe.find('a').each(function() {
          if ( this.href == TARGET_URL ) {
             // do something
          }
     });
  }
}

答案 1 :(得分:0)

插入iframe后,您可以像在jquery

中一样从其ID中获取iframe
$('#tumblr_controls')

并获取源网址只需使用jquery的attr

var source = $('#tumblr_controls').attr('src');

jsfiddle.net上的工作演示

答案 2 :(得分:0)

您的iframe是另一个文档,因此您应该将其视为......

$(document).ready(function(){
  $("#iframe).load(function(){
   //do stuff
  })
});