pass value/variable from fancybox iframe to parent

后端 未结 2 1051
天命终不由人
天命终不由人 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条回答
  •  没有蜡笔的小新
    2020-12-10 22:25

    Some clarifications :

    • You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
    • You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
    • You should use .html() or .text() to get the contents of any element other than input,

    example: having this html code

    hola

    ... and this jQuery code

    var temp = $(".test").html();
    

    ... temp will return hola.

    On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.

    so, having this html in the child (iframed) page for instance

    GOOGLE

    JSFIDDLE

    STACKOVERFLOW

    You could set this jQuery in your parent page to get the contents of any clicked element in your child page :

    var _tmpvar; // the var to use through the callbacks
    jQuery(document).ready(function ($) {
        $(".fancybox").fancybox({
            type: "iframe",
            afterShow: function () {
                var $iframe = $('.fancybox-iframe');
                $iframe.contents().find(".members_body p").each(function (i) {
                    $(this).on("click", function () {
                        _tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
                        $.fancybox.close();
                    }); // on click
                }); // each
            },
            afterClose: function () {
                $('#form input[name=username]').val(_tmpvar);
            }
        });
    }); // ready
    

    Notice that we declared the var _tmpvar globally so we can use it within different callbacks.

    See JSFIDDLE

提交回复
热议问题