【问题标题】:Trigger function from within iframe to parent从 iframe 到父级的触发函数
【发布时间】:2013-11-18 01:46:19
【问题描述】:

我在iframe 中有以下功能:

function modalHgt() {
    windowHeight = $(window.parent).height();
    complementHeight = $('#complement').outerHeight(true)+20;
    popupHeight = $('#main').outerHeight(true);
    if ((popupHeight) > (windowHeight-complementHeight)){
        popupHeight = windowHeight-complementHeight;
    } else {
        popupHeight = $('#main').outerHeight(true)+15;
    }
    $("#sbox-window", top.document).height(popupHeight);
}

我需要在调整大小时调用相同的函数在父。我尝试了以下方法,但它不起作用:

$(function() {
    var modalHeightTimer;
    $(window).resize(function() {
        clearTimeout(modalHeightTimer);
        modalHeightTimer = setTimeout($.modalHgt, 50);
    });
});

您能否建议我如何在父级中调用 iframe 函数?

【问题讨论】:

    标签: javascript jquery iframe resize


    【解决方案1】:
    modalHeightTimer = setTimeout(window.parent.modalHgt, 50);
    

    让父级在 iframe 中调用函数:

    $('#theIFrame')[0].contentWindow.functionName();
    

    但是看起来你的 iframe 的函数是一个匿名的就绪函数,所以如果你想让父级调用它,你必须在 iframe 中实际声明一个函数,比如

    function functionName() { //contents; }
    

    如果你想从父级调用它

    【讨论】:

    • 我收到以下错误:Error: useless setTimeout call (missing quotes around argument?)
    • 我想我误解了。我以为您想在 iframe 中调用父函数。但我认为实际上,您想从父文档中调用 iframe 中的函数?
    • 完全正确。这就是我所追求的。我尝试了你的建议,但我得到了:contentWindow is undefined - 正如你在我的 OP 中看到的那样,我已经在 iframe 中声明了这样的函数function functionName() { //contents; }
    • 如果我写这个就可以了:$('iframe[name=contentFrame]').get(0).contentWindow.modalHgt(); 感谢这篇文章:stackoverflow.com/questions/10167460/…
    • .contentWindow 的东西是 javascript。使用get(0)[0]jQuery 选择器的第0 个(第一个)匹配元素作为JavaScript 对象返回。这是一个相当常见的技巧,用于访问由jQuery 选择的对象的JavaScript Only 方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多