Calling function in dynamically created iFrame, fr

2019-06-08 12:46发布

Summary:

Using jQuery UI dialogs and a dynamically created iFrame, is it possible to call a function inside the iFrame from one of the buttons defined in the .dialog

Details:

I'm only just starting to cut my teeth with jQuery and jQuery UI, and I am trying to convert an existing application over to using the .dialog functionality.

The previous plugin that I was using for "inline popup windows" was good, but jQuery cannot co-exist with it as they both use the $() method. I am aware you can avoid conflicts with other libraries, but I thought it was easier to move over to jQuery lock-stock-and-barrel, rather than make them co-exist.

The advantage of the previous plugin was the ability to specify the content of the popup to be either an existing <div> on the page, direct HTML code or (most importantly to me) the URL to a different page.

This answer really helped me get the last of those abilities working, and this is what I currently have...

$(document).ready(function () {
  var iframe = $('<iframe id="myFrame" width="100%" height="100%" frameborder="0" marginwidth="0" marginheight="0"></iframe>');
  var dialog = $('<div id="myDiv"></div>').append(iframe).appendTo("body").dialog({
    autoOpen: false,
    modal: true,
    resizable: true,
    width: 600,
    height: 600,
    title: "My Popup",
    close: function () {
      iframe.attr("src", "");
    },
    buttons: [{ text: "Call iFrame Function",
                click: function () { alert($("#myFrame").contentWindow); }
              },
              { text: "Close Popup",
                click: function () { $("#myDiv").dialog("close"); }
              }]
  });
  iframe.attr({ src: "SubPage.html" });
  dialog.dialog("open");
});

What I cannot work out is...

How can I run javascript in the iFrame that has been created dynamically by the jQuery, via a button click??

Why is the .contentWindow in $("#myFrame").contentWindow always undefined? (I can confirm that $("#myFrame") returns the iframe in question.)

1条回答
爷、活的狠高调
2楼-- · 2019-06-08 13:02

Edit: The reason $("#myFrame").contentWindow is undefined is that the jQuery object consisting of the iframe element does not have a contentWindow property. You need to get(0) on it to get the actual window element, on which you can call Javascript functions defined in that namespace.

$("#myFrame").get(0).contentWindow.myFunction(args);

To traverse and manipulate its DOM, use this to get your iframe's content document:

var framedoc = $("#myFrame").get(0).contentDocument || $("#myFrame").get(0).contentWindow.document;

Then you should be able to manipulate it like a normal document, e.g.

$(framedoc).find("input#whatever").val(myInput).closest("form").submit()

Or whatever it is you're wanting to trigger.

查看更多
登录 后发表回答