回调函数值

Jas*_*lly -2 html javascript jquery jquery-ui javascript-framework

可能重复:
函数触发提前
调用函数值

我需要一些帮助.

在我的生活中,我不能想到这一点.我头上缠着它只是无济于事.

我想设置两个功能.

  1. function:select_date()与用户交互以从jQuery Date选择器中选择日期.如果对话框已关闭,则返回null.

  2. 然后是第二个功能:test()检查日期是否是picked/selected.

这是我的困境,当test()执行该功能时,会弹出一个警告框并说明"undefined"这意味着,我永远不会选择一个日期而且它始终存在"undefined"

我不明白我在这里做错了什么,一切对我来说都是合乎逻辑的.

<!DOCTYPE html>
<html>
<head>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.js"></script>

    <script type="text/javascript">

    function select_date() {
    var sdate

        $('#dd').dialog({
            autoOpen: true,
            modal: true,
            overlay: {
                opacity: 0.5,
                background: 'black'
            },
            title: "title",
            height: 265,
            width: 235,
            draggable: false,
            resizable: false
        });
        $('#d1').datepicker({
            onSelect: function () {
                $("#dd").dialog("close");
            }
        });
        return sdate
    }

    function test() {
    var x = select_date()

    alert(x)

    }

    </script>
    <style type="text/css">
    #d1 {font-size:64%;}
    </style>
</head>
<body>
<div id="dd">
<div id="d1">
</div>
</div>
<a href="javascript:test()">test</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Bre*_*dan 6

这是JavaScript的工作方式...... select_date()立即返回,因为.dialog().datepicker()是异步方法.return sdate甚至在发生任何事情之前被召唤.正确的方法是使用回调方法onSelect()

function select_date(callback) {
  $('#dd').dialog({
        autoOpen: true,
        modal: true,
        overlay: {
            opacity: 0.5,
            background: 'black'
        },
        title: "title",
        height: 265,
        width: 235,
        draggable: false,
        resizable: false
    });
    $('#d1').datepicker({
        onSelect: function () {
            $("#dd").dialog("close");
            callback($(this).datepicker('getDate'));
        }
    });
}

function test() {
  select_date(function(selected_date) { alert(selected_date); });
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是,如果没有选择日期并且对话框已关闭,则不会调用回调.您可以在对话框中为其添加一个事件侦听器,并callback使用null/undefined值调用它,但这取决于您.