简体   繁体   English

jQuery在单击按钮时返回父函数

[英]Jquery return to parent function on button click

I have a popup div like confirm to show like below 我有一个弹出div,如确认,如下所示

<div class='pop'>
    check me
    <span class="spok">Ok </span>
    <span class="spcancel">cancel </span>
</div>

Now this popUp will be open on some condition, and on button click I want to return some values to parent function 现在,此弹出窗口将在某些条件下打开,然后单击按钮,我想将一些值返回给父函数

Button events 按钮事件

$(".spok").click(function(){
    return 'OK';
});
$(".spcancel").click(function(){
    return 'CANCEL';
});

showPop method showPop方法

function showpop (){
   $('.pop').show();

}

now calling like this 现在这样打电话

var retval = showpop()
alert(retval);

But it seems I am no where close to my requirement. 但似乎我离我的要求还差得远。

Code on fiddle 小提琴上的代码

Fiddle 小提琴

Update 更新

Able to call back the function but.... When i tried to hide the popup it alerts as many times it has been called. 可以回调该函数,但是....当我尝试隐藏弹出窗口时,它会被调用多次。 Select Yes or no in dropdown then after click on Ok or cancel, two or three times, you will see effect 在下拉菜单中选择是或否,然后单击确定或取消两次或三次,您将看到效果

Updated fiddle 更新的小提琴

[Fiddle2][2]

The operation of the dialog & buttons is asynchronous. 对话框和按钮的操作是异步的。 Use callbacks (eg passed to the dialog) or events to broadcast the result. 使用回调(例如传递给对话框)或事件来广播结果。 One way is to provide a callback to your popup that gets called back with the result: 一种方法是提供对您的弹出窗口的回调,并返回结果:

function showpop (onclose){
   $('.pop').show();
    $(".spok").click(function(){
        onclose('OK');
    });
    $(".spcancel").click(function(){
        onclose('CANCEL');
    });   
}

$(document).ready(function(){
    var retval = showpop(function(retval){
        alert(retval);
    });
}); 

JSFiddle: http://jsfiddle.net/TrueBlueAussie/gp5emrm4/4/ JSFiddle: http : //jsfiddle.net/TrueBlueAussie/gp5emrm4/4/

Note: The event handlers for the click should be more specific to the dialog (probably use delegated events, attached to the popup instead): 注意:单击的事件处理程序应更特定于对话框(可能使用委托事件,而是附加到弹出窗口):

function showpop (onclose){
   $('.pop').show().on('click', 'span', function(){
        onclose($(this).attr('class'));   // or some other property of the button
    });
}

More practical example (using data- attributes): 更实际的示例(使用data-属性):

JEFiddle: http://jsfiddle.net/TrueBlueAussie/gp5emrm4/5/ JEFiddle: http : //jsfiddle.net/TrueBlueAussie/gp5emrm4/5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM