$ is not defined in iFrame

后端 未结 4 1952
别跟我提以往
别跟我提以往 2021-01-04 06:53

I have a page with an iframe in it. my iframe page is iframe.php and my main page is main.php when i load iframe.php directly my jquery code executes fine, but when I load m

相关标签:
4条回答
  • 2021-01-04 07:11

    I figured it out. In the iFrame I used

    var $ = parent.$;
    

    as well as giving any jquery calls the document for context. ie

    $("#element", document).doStuff();
    

    It's weird because the original way I had it (with jquery included in both pages) worked fine in Safari for Mac but in Firefox it gave me the error

    Error: c.defaultView.getComputedStyle(h, null) is null Source File: http://code.jquery.com/jquery-latest.pack.js Line: 16

    0 讨论(0)
  • 2021-01-04 07:14

    Upgrade to newer version f.e. https://code.jquery.com/jquery-2.1.3.min.js

    0 讨论(0)
  • 2021-01-04 07:17

    I was loading iframe in a webpage and I could find $ object using

    var $ = parent.$;
    

    but this was not performing selection on the elements of iFrame. Found below code to execute selector on the iFrame body

    if (typeof(jQuery) == "undefined") {
        var iframeBody = document.getElementsByTagName("body")[0];
        var jQuery = function (selector) { return parent.jQuery(selector, iframeBody); };
        var $ = jQuery;
    }
    

    Somehow the document object was also undefined.

    Source of above code: https://gist.github.com/843229

    Hope it helps someone.

    0 讨论(0)
  • 2021-01-04 07:17

    Bad news-- you can't use Jquery unless it's in the document. So, you're gonna have to load it regardless.

    There's actually no harm in including the jquery call in both documents. I have several clients who iFrame a portion of my company's app for marketing automation (which has it included) and also have Jquery included in their parent document, and it works just fine with no conflicts. From a load standpoint, assuming you're setup correctly, the hit will be negligible due to caching. So, include away.

    Rule of thumb on iFrames...think of them as separate pages inside your page. Yes, in some cases things carry over, but the document origin model prevents things like CSS from crossing between parent and child.

    0 讨论(0)
提交回复
热议问题