简体   繁体   中英

Jquery return to parent function on button click

I have a popup div like confirm to show like below

<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

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/

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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