$ is not defined in iFrame

后端 未结 4 1972
别跟我提以往
别跟我提以往 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题