Javascript 如何获取iframe的父元素(而不仅仅是窗口)?

Javascript 如何获取iframe的父元素(而不仅仅是窗口)?,javascript,jquery,Javascript,Jquery,类似于,但我的设置有点不同 我编写了这个函数: function ShowDialog(url, width, height, id, options) { var self = arguments.callee; if(!self.dialogs) self.dialogs = {}; var src = url + (url.indexOf('?') === -1 ? '?' : '&') + '_popup=1'; if(id) src += '&

类似于,但我的设置有点不同

我编写了这个函数:

function ShowDialog(url, width, height, id, options) {
    var self = arguments.callee;
    if(!self.dialogs) self.dialogs = {};

    var src = url + (url.indexOf('?') === -1 ? '?' : '&') + '_popup=1';
    if(id) src += '&_field=' + encodeURIComponent(id);

    if(url in self.dialogs === false) {
        var defaults = {
            width: width,
            height: height,
            modal: true,
            resizable: false,
            draggable: false,
            closeText: 'Close'
        };

        self.dialogs[url] = $('<div/>')
            .html('<iframe width="100%" height="100%" marginwidth="0" marginheight="0" frameborder="0" scrolling="auto" src="'+src+'">Your browser does not support iframes.</iframe>')
            .dialog(options ? $.extend(defaults, options) : defaults);
    } else {
        if(self.dialogs[url].data('reload')) {
            self.dialogs[url].data('reload', false).children('iframe').attr('src', src);
        }
        self.dialogs[url].dialog('open');
    }
    return false;
}

??我不知道这需要什么。某种对自身的引用<代码>窗口不起作用。

在iframe中,您可以像这样获得父DOM:

<button onclick="return ShowDialog('/companies/add', 400, 320, 'id_company');">New</button>
window.parent.frames[0].parentNode;
这假设父窗口中只有一个iframe,该iframe就是您进行此调用的源窗口

这里可能是(未经测试的)另一种方法,在父窗口中创建一个函数,如:

var findParent = function() {
    return $(this).parent();
}
然后在iframe内执行以下操作:

window.parent.findParent.call(window);
再次未经测试:-)

好的,第三次尝试

ShowDialog
函数中,而不是
return false
do:

返回自我

然后在iframe缓存中,返回一个变量,因此按钮如下所示:

<button onclick="return ShowDialog('/companies/add', 400, 320, 'id_company');">New</button>
window.parent.frames[0].parentNode;
New

因此,在这个按钮之前的iframe的某个地方,您将有一个
var obj

然后,无论何时需要iframe的父级,都可以执行以下操作:

对象对话框[窗口.位置.路径名]

此IMO应返回iframe的父级


再次未经测试:D

我认为这是我们所能做到的最好的:

<script type="text/javascript">
var $ = window.parent.jQuery;
$('.ui-dialog-content').filter(function(){return $(this).dialog('isOpen');}).dialog('close').data('reload', true);
</script>
(这是Django模板)

提供了IFrame元素

var parent = $(window.frameElement).parent();
只是by上的一个扩展,据我所知,它工作得很好。然而,在我发现这个方法之前,我必须“发明”一种使用jQuery的跨浏览器方式

我经常找到的解决方案是
parent.document
。这里的问题是,“如果我有多个iframe怎么办?”

因此,下面的片段

var parIframe = $(parent.document).find('iframe')
        .filter(function(i){ return $(this).contents()[0] == $(document)[0] });

.filter
方法用于将父窗口中每个iFrame的内容与当前iFrame的内容进行比较,从而只返回您正在查找的iFrame窗口。

是的……但我不喜欢这样假设。为什么不使用window.frameElement?(参考我的答案)我不知道它的存在,现在我学到了一些新的东西!那很好用。希望它是跨浏览器兼容的。我认为它相当兼容,因为我在大多数项目中都使用它。@Sarath:Mark说的是
跨浏览器
兼容性。你说得对,它不兼容跨域。(事实上,没有javascript代码是可用的,除非您在响应头中显示
访问控制允许源代码