pass value/variable from fancybox iframe to parent

后端 未结 2 1042
天命终不由人
天命终不由人 2020-12-10 21:28

I\'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.

Fancybox is launched from a link with

   class         


        
2条回答
  •  萌比男神i
    2020-12-10 22:19

    When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose

    $(document).ready(function() {
        $('a.fancybox').fancybox({
            openEffect:'fade',
            openSpeed:500,
            beforeClose: function() {
                // working
                var $iframe = $('.fancybox-iframe');
                alert($('input', $iframe.contents()).val());
            },
            afterClose: function() {
                // not working
                var $iframe = $('.fancybox-iframe');
                alert($('input', $iframe.contents()).val());
            }
        });
    });
    

    JSFiddle: http://jsfiddle.net/NXY7Y/1/

    EDIT:

    I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link http://jsfiddle.net/NXY7Y/13/

    Main page javscript:

    $(document).ready(function() {
        $('a.fancybox').fancybox({
            openEffect:'fade',
            openSpeed:500//,
            //beforeClose: function() {
            //    // working
            //    var $iframe = $('.fancybox-iframe');
            //    alert($('input', $iframe.contents()).val());
            //},
            //afterClose: function() {
            //    // not working
            //    var $iframe = $('.fancybox-iframe');
            //    alert($('input', $iframe.contents()).val());
            //}
        });
    });
    
    function setSelectedUser(userText) {
        $('#username').val(userText);
    }
    

    No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:

    $(document).ready(function() {
        $('a.insert_single').click(function() {
            parent.setSelectedUser($(this).text());
            parent.$.fancybox.close();
        });
    });
    

提交回复
热议问题