calling a functions value [duplicate]

江枫思渺然 提交于 2019-12-20 08:09:58

问题


Possible Duplicate:
Function triggering early

I have whipped up this code, but why on earth would it be alerting me that its undefined even though I have never even got a chance to click on and select a date from the UI date picker when I call the function test()?

Doesn't seem to make sense with me?

var sdate

function test() {
    alert(select_date())
}

function select_date() {
    $('#dd').dialog({
        autoOpen: true,
        modal: true,
        overlay: {
            opacity: 0.5,
            background: 'black'
        },
        title: "title",
        height: 265,
        width: 235,
        draggable: false,
        resizable: false
    }); //end of dialog

    $('#d1').datepicker({
        onSelect: function() {
            sdate = $(this).val();
            $("#dd").dialog("close");
        }
    });
    return sdate
}​

回答1:


onSelect is an event callback, you are trying to return a value before it knows what to do. it's not going to be possible to have your test() return the value, because it comes later.

you should do your alert or whatever logic from within the event callback:

$('#d1').datepicker({
    onSelect: function() {
        sdate = $(this).val();
        $("#dd").dialog("close");
        alert(sdate);
        // or your own function
        someOtherTest(sdate);
    }
});

-

function someOtherTest(date) {
    alert(date);
}


来源:https://stackoverflow.com/questions/12202188/calling-a-functions-value

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