如何在单击位于Iframe内的锚标记时执行jQuery函数

时间:2018-01-23 15:07:23

标签: javascript jquery html

我的应用程序中有一个网页,我在页面加载时加载了iframe。 iframe显示在我们的应用程序中创建的自定义文档。 iframe名称是动态生成的,内容由自定义Javascript框架加载。 该文件有两个主要的垂直部分。 第一个垂直部分具有向用户显示的页面列表,以便用户可以导航到第n页面。

<iframe id="xyz15031550Iframe0" name="xyz15031550Iframe0" scrolling="no" src="/displaydocument/2339389/15031550?doc=100" style="height: 989px;" width="1277px" height="963px" frameborder="0">

<div class="containerFull">

<div class="allPages" id="allPages">

   <a class="pagenumber_001" href="/document/2339389/15031550">Page 1</a>
   <a class="pagenumber_002" href="/document/2339389/15031550">Page 2</a>
   <a class="pagenumber_003" href="/document/2339389/15031550">Page 3</a>

</div>
<div id="pagesArea">
  <div class="docPage" id="page_body_001">
    <div id="docPageSection-001-1">
      PAGE CONTENT
    </div>
  </div>
</div>
</div>
</iframe>

在页面加载时,iframe将显示第1页。

通过单击锚标记,用户可以导航到任何页面。单击锚标记后,将重新加载iframe,并将页面详细信息发送到后端。

由于某些页面的宽度较大且用户不希望存在水平滚动,因此我调整了iframe容器的宽度和两个div,以使它们在窗口上正确显示。

`

<script src="adjust_doc_view.js"></script>
// the above script contains a jQuery function called updateView which basically 
// has css related jQuery statements.
jQuery(window).on('load', function () {
    setTimeout(updateView, 100); // timeout is used to wait for the iframe to load completely
});

`

我面临的问题是在页面加载时只触发一次updateView。在随后重新加载Iframe时,不会调用updateView。那是因为我没有加载整个页面。我有其他div在iframe之上是常数。让我知道如何在每次重新加载iframe内容时触发updateView。

我尝试在锚定点击事件上添加onclick功能,但它只能运行一次。我不知道为什么。

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>

jQuery(window).on('load', function () {
    // use setTimeout() to execute
    // Setting the timeout to zero as no delay is experienced in this page.
    setTimeout(updateView, 0);

    jQuery("div[id^='artifactDiv']").find("iframe[id^='xyz']").contents().find("a[class^='pagenumber']").on('click', function() {
        setTimeout(updateView, 1000);
    });

    jQuery("div[id^='artifactDiv']").find("iframe[id^='xyz']").contents().find("div[id^='docPageSection']").on('load', function() {
        setTimeout(updateView, 1000);
    });
});

请帮帮我。如果我做错了,请纠正我。 提前致谢。

2 个答案:

答案 0 :(得分:1)

如何将onload属性添加到iframe并从那里调用updateView()

<iframe onload="setTimeout(function() { updateView(); }, 1000);" id="xyz15031550Iframe0" name="xyz15031550Iframe0" scrolling="no" src="/displaydocument/2339389/15031550?doc=100" style="height: 989px;" width="1277px" height="963px" frameborder="0"></iframe>

答案 1 :(得分:0)

您可以使用iframe中的ajaxComplete来触发更新:

$(function() { 
  // iframe in main page   
  $('iframe').on('load', function() {

     updateView()// first load update

    // reference to window and document inside frame
    var win = this.contentWindow || this,
      doc = this.contentDocument || this.contentWindow.document;

    // have to use iframe version of jQuery
    win.$(doc).ajaxComplete(function(event, xhr, settings) {
      // fires every time an ajax request completes in iframe
      updateView()
    });
  });
});

DEMO