调用函数值 [英] calling a functions value

查看:116
本文介绍了调用函数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

函数提前触发


我已经提出了这段代码,但为何在地球上它会提醒我,它的未定义,即使我没有机会点击并从UI日期选择器中选择一个日期,当我调用函数test()?



  var sdate 

函数test( ){
alert(select_date())
}

函数select_date(){
$('#dd')。dialog({
autoOpen :true,
modal:true,
覆盖:{
不透明度:0.5,
背景:'black'
},
title:title ,
height:265,
width:235,
draggable:false,
resizable:false
}); //对话结束
$ b $('#d1')。datepicker({
onSelect:function(){
sdate = $(this).val();
$(#dd)。dialog(close);
}
});
return sdate
}


解决方案

onSelect 是一个事件回调,你试图在它知道该怎么做之前返回一个值。它不可能让你的 test()返回值,因为它迟一点。



你应该在事件回调中做你的警戒或任何逻辑:

  $('#d1')。datepicker({
onSelect:function(){
sdate = $(this).val();
$(#dd)。dialog(close);
alert(sdate) ;
//或您自己的函数
someOtherTest(sdate);
}
});

-

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


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
}​

解决方案

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);
}

这篇关于调用函数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆