Jquery run function from child window in parent window

亡梦爱人 提交于 2020-01-02 11:06:14

问题


I have a popup window and I want to run a function from in the parent window.

In the child I have:

$(document).ready(function(){
    parent.$.fn.guestFromPop('Action');
});

In the parent I have:

$(document).ready(function(){
    function guestFromPop(data) {
        alert(data);
    }
});

The problem is when parent.$.fn.guestFromPop('Action'); I never see the alert, nothing happens. Am I doing something wrong?


回答1:


This doesn't declare the function $.fn.guestFromPop:

$(document).ready(function(){
  function guestFromPop(data) {
    alert(data);
  }
});

...all it does is declare guestFromPop(), a function only available inside that document.ready handler. You would need to declare the function you're after instead:

$.fn.guestFromPop = function(data) {
  alert(data);
};

Though, this isn't really correct either, since it wont be called on a jQuery element, you may want something as simple as :

function guestFromPop(data) {
  alert(data);
}

called by:

parent.guestFromPop('Action');



回答2:


(function(){
$.fn.TestFunction=function(SampleData)
{
alert(SampleData);
};
});

//callable in other parent page or iframe //

(function(){
$.fn.TestFunction("sdfsdfsfsfsd");

});



回答3:


I had the same problem. Figured it out. The problem with your code is that you're not referring to the right window to call the function from. To get from a console to it's parent you'll need 'opener', not 'parent'.

So instead of parent.guestFromPop('Action'), you need to call this:

$(self.window.opener.document).guestFromPop('Action');

That should refer to the correct function. It worked for me! ;-)




回答4:


guestFromPop = function(data) {
  alert (data)
}

call from iframe:

parent.guestFromPop(data);


来源:https://stackoverflow.com/questions/4589576/jquery-run-function-from-child-window-in-parent-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!